Hof*_*ann 5 javascript css jquery internet-explorer
我正在使用CSS content属性将一些值从我的LESS样式表传递给JavaScript(使用Canvas元素中的LESS中定义的一些颜色).为了让我的生活更轻松,我决定以简单的方式放置这些值,以便在JavaScript中解析它们.
少量代码:
div#colorChart-critical {
content:'@{critical-highest},@{critical-veryhigh},@{critical-high},@{critical-low},@{critical-medium},@{critical-verylow}';
}
Run Code Online (Sandbox Code Playgroud)
编译时带来以下CSS:
div#colorChart-critical6 {
content: '#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00';
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用jQuery读取它们:
$("div#colorChart-critical").css("content").split(",");
Run Code Online (Sandbox Code Playgroud)
问题是在IE9中调用由于某种原因$("div#colorChart-critical").css("content")返回字符串"normal".Opera,Firefox,Safari和Chrome工作正常.
为什么会在IE9中发生这种情况?
在IE9上解决这个问题?如果不是任何其他CSS属性我可以随机文本?
我可以使用类似的东西:
background: url(#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00);
Run Code Online (Sandbox Code Playgroud)
但这会在控制台上产生错误.
这是因为contentCSS2.1中的定义不适用于元素,仅适用于:before和:after伪元素.IE9就是跟随这里的CSS2.1规范,该规范强制要求的是content对元素进行计算到normal,始终.
我不知道为什么其他浏览器会返回你定义的值,特别是考虑到在这些浏览器上.css()使用getComputedStyle()它们.如果他们正在实施CSS2.1 content,那么他们通过不计算值来违反CSS2.1 normal.如果他们正在准备一个晚期的CSS3实现,无论可能是什么,那么它们在某种程度上在实际元素上实现它是有道理的......无论如何都要羞辱它们.
这让我想到另一点:如果你实际上并没有尝试使用CSS修改元素的内容,请不要使用content,即使它没有定义用于元素的事实是你正在使用的原因首先是这种技术.您可以尝试将这些颜色分配给某些类,创建隐藏元素并查询该元素的颜色样式.
BoltClock 的答案显示了我的问题的原因。我找到了一个解决方法,使用 font-family 而不是 content CSS 属性。
我的更少代码:
div#colorChart-maincolors {
font-family: '@{colorChart1},@{colorChart2},@{colorChart3},@{colorChart4},@{colorChart5},@{colorChart6}';
}
Run Code Online (Sandbox Code Playgroud)
编译成 CSS 后得到:
div#colorChart-maincolors {
font-family: '#c0392b,#2980b9,#2ecc71,#f1c40f,#ecf0f1,#34495e';
}
Run Code Online (Sandbox Code Playgroud)
可以使用以下方式获取字符串:
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
Run Code Online (Sandbox Code Playgroud)
函数removeQuotes 是必要的,因为每个浏览器都会在 getCompulatedStyle(以及扩展的 jQuery .css() 方法)的返回值中添加不同类型的引号。IE9添加了双引号,Webkit添加了单引号。
请参阅这篇有关 CSS 技巧的文章:http://css-tricks.com/making-sass-talk-to-javascript-with-json/了解更多信息。