检索CSS生成的内容

问题描述 投票:1回答:1

是否可以使用JavaScript在HTML文档中引用生成的内容?例如,我在文档中有一个数字

body {
  counter-reset: figures 0;
}

figcaption::before {
  counter-increment: figures;
  content: "Figure " counter(figures);
}
<figure>
  <img src="https://placehold.it/222x77" alt="222x77">
  <figcaption id="greyish"></figcaption>
</figure>
<p>Here in <span>Figure 1</span>, we see a greyish square.</p>

而且我也想在文本中使用图形的确切标题,我该怎么做?

我在代码段中硬编码了“图1”,但这不够灵活。如果这不是第一个数字怎么办?伪元素的getComputedStyle()也返回"Figure " counter(figures),因此并没有太大帮助。我想要文字文本“图1”。

javascript css pseudo-element getcomputedstyle
1个回答
0
投票

使用JavaScript函数迭代具有所需标签名称或类名称的元素

getElementsByTagName

    function init() {
      fignums = document.getElementsByTagName("span");

      for (i=0;i<fignums.length;i++) {
        fignums[i].innerHTML = "Figure " + (i+1);
      }
    }

getElementsByClassName

    function init() {
      fignums = document.getElementsByClassName("fignum");

      for (i=0;i<fignums.length;i++) {
        fignums[i].innerHTML = "Figure " + (i+1);
      }
    }

并通过body onload调用该函数

    <body onload='init()'>
      <figure>
        <img src="https://placehold.it/222x77" alt="222x77">
        <figcaption>Here in <span class='fignum'></span> we see a greyish square</figcaption>
      </figure>

      <figure>
        <img src="https://placehold.it/222x77" alt="222x77">
        <figcaption>This one is <span class='fignum'></span></figcaption>
      </figure>
    </body>
© www.soinside.com 2019 - 2024. All rights reserved.