setAttribute不适用于IE上的'style'属性

时间:2010-01-22 17:51:20

标签: javascript html internet-explorer

我正在将为Firefox编写的一段JS代码移植到Internet Explorer中。我遇到了使用setAttribute方法更改元素样式的问题,该方法适用于Firefox。

button.setAttribute('style', 'float: right;');

我尝试设置按钮的样式成员,它也不起作用。这是设置onclick事件处理程序的解决方案。

button.style = 'float: right;';

首先,我想知道上述问题的解决方案 其次是浏览器之间存在这些差异的维护列表吗?

6 个答案:

答案 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)

Internet Explorer中的

getAttributesetAttribute已损坏。

您要尝试实现的正确语法是:

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中有效。刚试了一下。

  1. 该方法传递样式名称和值
  2. 然后该方法检查是否有任何样式 如果不存在样式属性,则该方法仅设置样式并停止
  3. 如果存在样式属性,则属性中的所有样式都将拆分为数组
  4. 迭代数组,并使用新值
  5. 更新所有适用的样式定义
  6. 然后从元素
  7. 中删除style属性
  8. 将style属性添加回元素,并将其值设置为新信息 从数组中收集

答案 5 :(得分:0)

另一个改变样式属性的有用方法是使用方括号访问该属性。这对于访问属性是很有用的,因为属性的名称如果正常表示会产生语法错误。在Java中,完全可以允许使用具有数值,以数字开头的字母,符号和空格作为字符的属性,但是随后必须使用方括号访问属性。

node.style.z-index = 50;//Firefox says error, invalid assignment left hand side.

node.style["z-index"] = "50";//Works without error