[英]jQuery $().css(“content”) returning the string “normal” in IE9
我正在使用CSS content
属性将一些值从我的LESS样式表传递给JavaScript(使用Canvas元素中的LESS中定义的一些颜色)。 为了让我的生活更轻松,我决定以简单的方式放置这些值,以便在JavaScript中解析它们。
少量代码:
div#colorChart-critical {
content:'@{critical-highest},@{critical-veryhigh},@{critical-high},@{critical-low},@{critical-medium},@{critical-verylow}';
}
编译时带来以下CSS:
div#colorChart-critical6 {
content: '#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00';
}
然后我尝试使用jQuery读取它们:
$("div#colorChart-critical").css("content").split(",");
问题是在IE9中调用$("div#colorChart-critical").css("content")
由于某种原因返回字符串"normal"
。 Opera,Firefox,Safari和Chrome工作正常。
为什么会在IE9中发生这种情况?
在IE9上解决这个问题? 如果不是任何其他CSS属性我可以随机文本?
我可以使用类似的东西:
background: url(#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00);
但这会在控制台上产生错误。
这是因为CSS2.1中定义的content
不适用于元素,仅适用于:before
和:after
伪元素。 IE9只是遵循这里的CSS2.1规范,它要求元素的content
始终被计算为normal
。
我不知道为什么其他浏览器会返回你定义的值,特别是考虑到.css()
getComputedStyle()
在这些浏览器上使用了getComputedStyle()
。 如果他们正在实现CSS2.1 content
,那么他们通过不将值计算为normal
来违反CSS2.1。 如果他们正在准备一个晚期的CSS3实现,无论可能是什么,那么它们在某种程度上在实际元素上实现它是有道理的......无论如何都要羞辱它们。
这让我想到另一点:如果你实际上并没有尝试使用CSS来修改元素的content
,那么就不要使用content
,即使它没有定义用于元素的事实是你正在制作的原因首先使用这种技术。 您可以尝试将这些颜色分配给某些类,创建隐藏元素并查询该元素的颜色样式。
BoltClock答案显示了我的问题的原因。 我通过使用font-family而不是内容CSS属性找到了解决方法。
我的LESS代码:
div#colorChart-maincolors {
font-family: '@{colorChart1},@{colorChart2},@{colorChart3},@{colorChart4},@{colorChart5},@{colorChart6}';
}
编译成CSS的内容给出:
div#colorChart-maincolors {
font-family: '#c0392b,#2980b9,#2ecc71,#f1c40f,#ecf0f1,#34495e';
}
可以使用以下方式获取字符串:
removeQuotes= function(string) {
return string.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
};
removeQuotes($("#colorChart-maincolors").css("font-family")); //add a .split(',') to get the colors as an array
函数removeQuotes是必要的,因为每个浏览器在getComputedStyle的返回中添加不同类型的引号(并且通过扩展jQuery .css()方法)。 IE9添加了双引号,Webkit添加了单引号。
有关CSS技巧,请参阅此文章: http : //css-tricks.com/making-sass-talk-to-javascript-with-json/了解更多信息。
你可以使用replace(/["']/g, "")
从字符串中删除额外的引用
""string""
将更改为"string"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.