2012-03-12 20 views
0

我已经搜索过并且为此搜索了一些关于如何阅读CSS propeties但非允许读取伪类属性的许多答案。如何在javascript中读取Psuedo类的CSS属性

我已经使用了以下内容,以便我可以在多种产品上轻松地重用某些页面(固件/配置上传)。

.productname:before 
{ 
    content: "My Shiny New Product"; 
} 

然后

<span class="productname" /> 
在html

插入正确的名称。

当前向服务器发送固件更新时,没有在客户端浏览器上进行检查,并且服务器返回[请重新启动以控制...]或[这不是[产品名称]更新文件]。正如你可以想象的,固件更新可能相当大,如果通过3G传输需要一段时间。

我想从CSS中获取产品名称:在伪类之前允许我在发送之前检查上传文件的名称。我已经实施了这个JS Fiddle来说明这个问题。

我已经尝试将content属性直接放在.productname类(作为副本占位符)和FF,Opera和Safari将会读取此内容,但您猜对了它,IE返回undefined。

我知道我可以在JS中使用全局变量,可能必须这样做,但我宁愿将它定义在一个地方以避免潜在的错误。

那么有谁知道如何(或解决方法)读取伪CSS类的属性?

在此先感谢。

更新

因为我不能让IE8的一个解决方案,我已经改变使用下面的代码来代替。

window.addEvent("domready", 
function() 
{ 
    window.productName = "My Shiny New Product";  

    var def = '.productname:before { content: "'+window.productName+'"; }'; 

    var style = new Element("style"); 
    style.setAttribute("type", "text/css"); 
    if(style.styleSheet) 
    { 
    style.styleSheet.cssText = def; 
    } 
    else 
    { 
    style.innerHTML = def; 
    } 
    document.getElementsByTagName("head")[0].appendChild(style); 
    document.getElementsByTagName("head")[0].appendChild(style); 
}); 

参照本网站Dynamic SCRIPT and STYLE elements in IE

+0

可能重复http://stackoverflow.com/questions/311052/setting-css-pseudo-class-rules-from-javascript – Manishearth 2012-03-12 11:56:09

+0

你可能想看看http://stackoverflow.com/questions/1543648/how-to-get-a-text-before-given-element-using-jquery – bPratik 2012-03-12 11:56:40

+0

@bPratik - 感谢评论,但用途:在文本不在html文档之前,我不认为它可以是以这种方式访问​​。从Firebug和我的小提琴之前的兄弟姐妹(div)的内容是空的。 – Dampsquid 2012-03-12 12:05:20

回答

2

可以使用window.getComputedStyle。然而,an answer指出,一些浏览器可能不支持这一点,所以轻轻一点。 here's a demo

<span class="test" /> 
<span class="test" /> 
<span class="test" /> 

.test:before{ 
    content: "My Shiny New Product"; 
} 

$(function() { 

    //get all element class test 
    var test = $('.test'); 

    //each of them, alert the content 
    test.each(function() { 
     var style = window.getComputedStyle(this, "before"); 
     alert(style.content); 
    }); 
});​ 
+0

谢谢,但测试你的演示它只能在Safari中工作。 FF和Opera警报:无,并且IE失败且对象不支持该方法。 – Dampsquid 2012-03-12 12:13:18

+1

更改您的代码以使用getComputedStyle(this,“:before”);使得它可以在除IE之外的所有环境中工作,可悲的是90%以上的客户将使用IE,而大多数客户将无法切换到其他浏览器。 – Dampsquid 2012-03-12 12:29:03

+0

@Dampsquid我无法测试IE因为我没有IE:D。您可以检查用户的浏览器并使用“之前”或“之前”。 – Joseph 2012-03-12 20:03:02