59

我使用 CSScountercontent属性生成标题和图形的编号:

img.figure:after {
  counter-increment: figure;
  content: "Fig. " counter(section) "." counter(figure);
}

这(假设是适当的浏览器)在任何图像之后给出了一个很好的标签“图 1.1”、“图 1.2”等等。

问题:如何从 Javascript 访问它?问题是双重的,因为我想访问某个计数器的当前值(在某个 DOM 节点上)CSS 生成的内容的值(在某个 DOM 节点上),或者显然,这两个信息。

背景:我想在链接后面附加适当的数字,如下所示:

<a href="#fig1">see here</h>
------------------------^ " (Fig 1.1)" inserted via JS

据我所见,归结为这个问题:我可以访问contentcounter-increment通过getComputedStyle

var fig_content = window.getComputedStyle(
                    document.getElementById('fig-a'),
                    ':after').content;

但是,这不是实时值,而是样式表中声明的值。我找不到任何接口来访问真实的实时值。在计数器的情况下,甚至没有真正的 CSS 属性可供查询。

编辑:深入挖掘 DOM 规范,我发现了 DOM Level 2 Style Counter interface。这似乎a)允许访问当前的计数器值和b)至少在Firefox中实现。但是,我不知道如何使用它。在这个 Firebug 输出之后,我目前的方法悲惨地死了:

// should return a DOM 2 Counter interface implementation...
window.getComputedStyle(fig_a_element, ':after')
      .getPropertyCSSValue("counter-increment")[0]
      .getCounterValue();

[Exception... "Modifications are not allowed for this document" code: "7"
 nsresult: "0x80530007 (NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR)"
 location: "http://localhost/countertest.html Line: 71"]

任何想法,如何将其变为现实,将不胜感激。

编辑 2:显然我误解了 DOM Level 2 Style 的 Counter 对象。它也没有返回当前计数器值的属性。这使得上述方法无效。

新方法:是否有可能通过 DOM 读取伪元素的内容?也就是说,我可以选择伪元素(treeWalker想到)然后得到它nodeValue吗?(如果您现在开始输入'jQuery',请重新考虑将该术语更改为'Sizzle' ...)

4

4 回答 4

24

我找不到任何接口来访问真实的实时值。[柜台的]

是的。我不认为有一个。对不起。

我唯一能想到的就是在文档中的元素之前遍历每个元素(包括它的:before/:after伪元素),寻找计数器并加起来有多少。

显然这很可怕。如果您要尝试重现浏览器自己的counter机制,那么只需将其替换为您自己的基于脚本的计数器可能会更容易(并且更兼容,因为 IE<=7 缺乏计数器/内容支持)。例如。类似于:

<a href="#prettypicture">this</a>

<div class="counter level=0">...</div>
<img id="prettypicture" class="counter level=1" alt="ooo, pretty"/>
window.onload= function() {
    var counters= Node_getElementsByClassName(document.body, 'counter');
    var indices= [];
    for (var counteri= 0; counteri<counters.length; counteri++) {
        var counter= counters[counteri];

        var level= Element_getClassArgument(counter, 'level');
        while (indices.length<=level)
            indices.push(0);
        indices[level]++;
        indices= indices.slice(level+1);
        var text= document.createTextNode('Figure '+indices.join('.'));
        counter.parentNode.insertBefore(text, counter.nextSibling);

        if (counter.id!=='') {
            for (var linki= document.links.length; linki-->0;) {
                var link= document.links[i];
                if (
                    link.hostname===location.hostname && link.pathname===location.pathname &&
                    link.search===location.search && link.hash==='#'+counter.id
                ) {
                    var text= document.createTextNode('('+indices.join('.')+')');
                    link.parentNode.insertBefore(text, link.nextSibling);
                }
            }
        }
    }
};
于 2010-04-16T10:26:05.270 回答
15

读这个:

生成的内容不会改变文档树。特别是,它不会被反馈给文档语言处理器(例如,用于重新解析)。


样式表中指定的内容不会成为 DOM 的一部分。

所以出于这个原因,getComputedStyle 在这种情况下将不起作用;我认为唯一的方法是按照 下面的描述执行经典循环!

于 2010-05-24T23:18:29.200 回答
2

我会将您的 css 移植到 Javascript,这使您能够获得图形标题,还可以获得更大的浏览器覆盖率。使用 jQuery 你会做这样的事情:

$(function() {
  var section = 0;
  $(".section").each(function() {
    section++;
    var figure = 0;
    $(this).find("img.figure").each(function() {
      figure++;
      var s = "Fig. " + section + "." + figure;
      $(this).attr({alt:s}).after(s);
    });
  });
});

然后你可以这样做:

<div class="section">blabla <img id="foo" src="http://www.example.com/foo.jpg"></div>
<p>Lorem ipsum dolor sit amet <a href="#foo" class="figurereference">see here</a></p>

<script type="text/javascript">
  $(function() {
    $("a.figurereference").each(function() {
      var selector = $(this).attr("href");
      var $img = $(selector);
      var s = $(this).text() + " (" + $img.attr("alt") + ")";
      $(this).text(s);
    });
  });
</script>

虽然我同意使用 CSS 来做这件事会非常整洁。

于 2010-05-18T09:13:44.037 回答
-1

我找不到任何接口来访问真实的实时值。

如果您无法从中获得价值window.getComputedStyle,那似乎是不可能的。

更重要的是,虽然它可以做到,但我认为这可能是在滥用 CSS,因为此时您正在打破内容和表示之间的障碍。

查看这个相关问题CSS“内容”属性有什么好的用途?

于 2010-04-16T10:17:25.753 回答