我已经搜索了SO并在谷歌上搜索了这个,关于如何读取CSS属性有很多答案,但不允许读取伪类属性。
我使用了以下内容,可以在许多产品上轻松地重用某些页面(固件/配置上传)。
.productname:before
{
content: "My Shiny New Product";
}
然后
<span class="productname" />
在html中插入正确的名称。
目前,当向服务器发送固件更新时,客户端浏览器上没有进行检查,服务器返回[请重新启动以继续…]或[这不是[产品名称]更新文件]。正如你可以想象的,固件更新可能相当大,如果通过3G传输需要一些时间。
我想从CSS:before pseudo类中获取productname,以便在发送之前检查上传文件名。我已经实现了这个JS Fiddle来说明这个问题。
我已经尝试过将content属性直接放在.productname类上(作为副本占位符),FF、Opera和Safari会读取此属性,但您猜到IE返回未定义。
我知道我可以在JS中使用全局var,可能必须这样做,但我宁愿在一个地方定义它,以避免潜在的错误。
那个么,有人知道如何(或变通方法)读取:伪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);
} );
参考本站点IE中的动态脚本和STYLE元素
您可以使用window.getComputedStyle。但是,有一个答案指出,有些浏览器可能不支持这一点,所以请谨慎行事。这是的演示
<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);
});
});