【发布时间】:2013-12-24 01:00:42
【问题描述】:
我正在使用this script 提取页面上元素的样式信息,然后将这些样式应用于第二个元素,但由于某种原因,它仅适用于 Chrome 和 Safari [不适用于 Firefox 或 Internet Explorer ]。这是有问题的,因为我主要需要 Internet Explorer。
这是演示:http://jsfiddle.net/J3tSx/1/
脚本:
$(document).ready(function() {
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
/*
$("#test_div").click(function() {
alert("clicked");
if (!$(this).hasClass("hovered")) {
alert("detected no hovered class");
$(this).addClass("hovered");
alert("added hovered class");
var hoverStyle = css($("#test_div"));
alert("created the hoverStyle variable");
$("#second_div").css(hoverStyle);
alert("applied the hoverStyle variable to #second_div");
}
});
*/
var hoverStyle = css($("#test_div"));
alert("created the hoverStyle variable");
$("#second_div").css(hoverStyle);
alert("applied the hoverStyle variable to #second_div");
});
HTML:
<section id="test_div">
</section>
<section id="second_div">
</section>
更新:奇怪的是 IE 和 Firefox 都没有抛出任何类型的错误。他们只是表现得好像#test_div 没有样式,因此没有样式被添加到#second_div。很奇怪。
更新 2:我刚刚注意到这段代码:
var s = {};
if (!css) return s;
我认为这可能与它有关。
我尝试过的事情
- 更改部分的名称,以摆脱 _
- 改用旧版本的 jQuery
- 将代码的位置从身体移动到头部等
【问题讨论】:
标签: jquery css internet-explorer webkit