如何使用JavaScript访问CSS生成的内容 [英] How to access CSS generated content with JavaScript

查看:107
本文介绍了如何使用JavaScript访问CSS生成的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CSS的计数器内容的属性生成我的标题和数字的编号:

  img.figure:after {
counter-increment:figure;
内容:图计数器(部分)。计数器(图);
}

这(假定适当的浏览器)给出了一个很好的标签图1.1 图1.2等等。



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



背景:我想追加将反向引用连接到数字的适当数字,如下所示:

 < a href =#fig1> see这里< / h取代; 
------------------------ ^(图1.1)通过JS
插入
/ pre>

据我所见,它归结为这个问题:
我可以访问 getComputedStyle 或 counter-increment

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

但是,这不是 live 值,样式表。我找不到任何界面来访问真实实时值。在柜台的情况下,甚至没有一个真正的CSS属性来查询。



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

  //应该返回一个DOM 2 Counter接口实现... 
window.getComputedStyle(fig_a_element,':after')
.getPropertyCSSValue(counter-increment)[0]
.getCounterValue();

[异常...本文档不允许修改代码:7
nsresult:0x80530007(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR)
位置:http:// localhost / countertest.html行:71]

任何想法,如何才能带来生活非常感谢。



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



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

解决方案


我找不到任何界面来访问真正的实时价值。 [柜台]


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



我唯一可以想到的是通过每个元素(包括它的:before /在$ / code $伪元素之前)文档中的元素之前,寻找计数器并加起来有多少。



<显然这是可怕的。如果您要尝试重现浏览器自己的计数器机制,则可能会更容易(并且更加兼容,因为IE< = 7缺乏计数器/内容支持)只需用自己的基于脚本的计数器替换它。例如。以下行:

 < a href =#prettypicture>此< / a> 

< div class =counter level = 0> ...< / div>
< img id =prettypictureclass =counter level = 1alt =ooo,pretty/>





  window.onload = function(){
var counters = Node_getElementsByClassName(document.body,'counter');
var indexes = [];
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);
}
}
}
}
};


I generate the numbering of my headers and figures with CSS's counter and content properties:

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

This (appropriate browser assumed) gives a nice labelling "Fig. 1.1", "Fig. 1.2" and so on following any image.

Question: How can I access this from Javascript? The question is twofold in that I'd like to access either the current value of a certain counter (at a certain DOM node) or the value of the CSS generated content (at a certain DOM node) or, obviously, both information.

Background: I'd like to append to links back-referencing to figures the appropriate number, like this:

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

As far as I can see, it boils down to this problem: I could access content or counter-increment via getComputedStyle:

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

However, this is not the live value, but the one declared in the stylesheet. I cannot find any interface to access the real live value. In the case of the counter, there isn't even a real CSS property to query.

Edit: Digging deeper and deeper through the DOM specs, I found the DOM Level 2 Style Counter interface. This seems to a) allow access to the current counter value and b) be implemented in Firefox, at least. However, I have no idea on how to use it. My current approach died tragically after this Firebug output:

// 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"]

Any idea, how this could be brought to life would be highly appreciated.

Edit 2: Apparently I misinterpreted the Counter object of DOM Level 2 Style. It, too, has no property to return the current counter value. This makes the above approach invalid.

New approach: Is there a possibility to read the content of a pseudo-element via the DOM? That is, can I select the pseudo-element (treeWalker comes to mind) and then get its nodeValue? (If you start to type 'jQuery' now, please reconsider to change that term into 'Sizzle'...)

解决方案

I cannot find any interface to access the real live value. [of the counter]

Yeah. I don't think there is one. Sorry.

The only thing I can think of would be to go through every element (including its :before/:after pseudo-elements) before the element in the document, looking for counters and adding up how many there are.

Obviously that's hideous. If you're going to try to reproduce the browser's own counter mechanism it would probably be easier (and much more compatible, given IE<=7's lack of counter/content support) to just replace it with your own script-based counters. eg. something along the lines of:

<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);
                }
            }
        }
    }
};

这篇关于如何使用JavaScript访问CSS生成的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆