我正在将为Firefox编写的一段JS代码移植到Internet Explorer中。我遇到了使用setAttribute
方法更改元素样式的问题,该方法适用于Firefox。
button.setAttribute('style', 'float: right;');
我尝试设置按钮的样式成员,它也不起作用。这是设置onclick
事件处理程序的解决方案。
button.style = 'float: right;';
首先,我想知道上述问题的解决方案 其次是浏览器之间存在这些差异的维护列表吗?
答案 0 :(得分:34)
因为风格本身就是一个对象。你想要的是:
button.style.setAttribute('cssFloat','right');
但IE不支持样式对象的setAttribute。所以使用完全跨浏览器支持:
button.style.cssFloat = 'right';
至于参考,我总是去www.quirksmode.org。具体来说:http://www.quirksmode.org/compatibility.html。点击所有与DOM相关的东西。
最后,要设置多个属性,我通常会使用以下内容:
function setStyle(el,spec) {
for (var n in spec) {
el.style[n] = spec[n];
}
}
用法:
setStyle(button,{
cssFloat : 'right',
border : '2px solid black'
});
注意:object.attribute = 'value'
虽然适用于所有浏览器但可能并不总是适用于非HTML DOM对象。例如,如果您的文档包含需要使用javascript操作的嵌入式SVG图形,则需要使用setAttribute
来执行此操作。
答案 1 :(得分:8)
您需要使用cssText
button.style.cssText = 'float: right;';
答案 2 :(得分:6)
getAttribute
和setAttribute
已损坏。
您要尝试实现的正确语法是:
button.style.cssFloat = 'right';
问题的正确解决方案更可能是:
button.className = 'a class that matches a pre-written CSS rule-set';
答案 3 :(得分:2)
我注意到setAttribute只在属性不存在时才在IE中工作。 因此,请使用remove属性,然后使用set属性。
没有测试过这个bug,但从概念上讲我认为这样可行:
注意 - 这被写入存在于具有名为'element'的属性的对象中。
//Set Property
this.setProperty = function (a, b) {
var c = this.element.getAttribute("style");
var d;
if (!c) {
this.element.setAttribute("style", a + ":" + b);
return;
} else {
d = c.split(";")
}
for (var e = 0; e < d.length; e++) {
var f = d[e].split(":");
if (f[0].toLowerCase().replace(/^\s+|\s+$/g, "").indexOf(a.toLowerCase().replace(/^\s+|\s+$/g, "")) == 0) {
d[e] = a + ":" + b
}
}
d[d.length] = a + ":" + b;
this.element.setAttribute("style", d.join(";"))
}
//Remove Property
this.removeProperty = function (a) {
var b = this.element.getAttribute("style");
var c;
if (!b) {
return
} else {
c = b.split(";")
}
for (var d = 0; d < c.length; d++) {
var e = c[d].split(":");
if (e[0].toLowerCase().replace(/^\s+|\s+$/g, "").indexOf(a.toLowerCase().replace(/^\s+|\s+$/g, "")) == 0) {
c[d] = ""
}
}
this.element.removeAttribute("style");
this.element.setAttribute("style", c.join(";").replace(";;", ";"))
}
答案 4 :(得分:1)
它在IE中有效。刚试了一下。
答案 5 :(得分:0)
另一个改变样式属性的有用方法是使用方括号访问该属性。这对于访问属性是很有用的,因为属性的名称如果正常表示会产生语法错误。在Java中,完全可以允许使用具有数值,以数字开头的字母,符号和空格作为字符的属性,但是随后必须使用方括号访问属性。
node.style.z-index = 50;//Firefox says error, invalid assignment left hand side.
node.style["z-index"] = "50";//Works without error