Javascript setAttribute 不适用于 IE 上的“样式”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2119300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:49:19  来源:igfitidea点击:

setAttribute is not working for 'style' attribute on IE

javascripthtmlinternet-explorer

提问by Ali Nadalizadeh

I'm porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttributemethod which was working on Firefox.

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

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

I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclickevent handler.

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

button.style = 'float: right;';

First I wanna know the solution for the above problem and
Second are there any maintained lists for these differences between browsers ?

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

回答by slebetman

Because style itself is an object. What you want is:

因为风格本身就是一个对象。你想要的是:

button.style.setAttribute('cssFloat','right');

But IE doesn't support setAttribute for style objects. So use the fully cross-browser supported:

但是 IE 不支持样式对象的 setAttribute。所以使用完全支持的跨浏览器:

button.style.cssFloat = 'right';

As for reference, I always go to www.quirksmode.org . Specifically: http://www.quirksmode.org/compatibility.html. Click on all the DOM related stuff.

至于参考,我总是去 www.quirksmode.org 。具体来说:http://www.quirksmode.org/compatibility.html。单击所有与 DOM 相关的内容。

And finally, to set multiple attributes I usually use something like:

最后,要设置多个属性,我通常使用以下内容:

function setStyle(el,spec) {
    for (var n in spec) {
        el.style[n] = spec[n];
    }
}

usage:

用法:

setStyle(button,{
    cssFloat : 'right',
    border : '2px solid black'
});

Note: object.attribute = 'value'although works in all browsers may not always work for non-HTML DOM objects. For example, if your document contains embedded SVG graphics that you need to manipulate with javascript you need to use setAttributeto do it.

注意:object.attribute = 'value'虽然适用于所有浏览器,但不一定适用于非 HTML DOM 对象。例如,如果您的文档包含需要使用 javascript 操作的嵌入式 SVG 图形,则您需要使用setAttribute它来执行此操作。

回答by Alex Z

You need to use cssText

你需要使用 cssText

 button.style.cssText = 'float: right;';

回答by Quentin

getAttributeand setAttributeare broken in Internet Explorer.

getAttributesetAttribute在 Internet Explorer 中损坏。

The correct syntax for what you are trying to achieve is:

您要实现的正确语法是:

button.style.cssFloat = 'right';

The correct solution to the problem is more likely to be:

问题的正确解决方案更有可能是:

button.className = 'a class that matches a pre-written CSS rule-set';

回答by Chris Shelton

I noticed that setAttribute works in IE only when the attribute does not already exist. Therefore, use remove attribute and then use set attribute.

我注意到 setAttribute 仅在该属性不存在时才在 IE 中工作。因此,使用 remove 属性,然后使用 set 属性。

Haven't tested this for bugs, but conceptually I think this will work:

尚未测试此错误,但从概念上讲,我认为这会起作用:

NOTE- this was written to exist inside object that had property called '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(";;", ";"))
}

回答by user1931270

It does work in IE. Just tried it out.

它在 IE 中确实有效。刚刚试了一下。

  1. The method is passed a style name and a value
  2. The method then checks to see if there are any styles If no styles attribute exists, then the method simply sets the style and stops
  3. If a style attribute exists, all the styles in the attribute are split into an array
  4. The array is iterated and all applicable style definitions are updated with the new value
  5. The style attribute is then removed from the element
  6. The style attribute is added back to the element with its values set to the new info gathered from the array
  1. 该方法被传递一个样式名称和一个值
  2. 该方法然后检查是否有任何样式如果不存在样式属性,则该方法仅设置样式并停止
  3. 如果存在样式属性,则将该属性中的所有样式拆分为一个数组
  4. 数组被迭代,所有适用的样式定义都用新值更新
  5. 然后从元素中删除样式属性
  6. style 属性被添加回元素,其值设置为从数组中收集的新信息

回答by Andrew S

Another useful way to mutate a style property is using the square brackets to access the property. This is useful for accessing properties which because of their name would give a syntax error if expressed normally. In JavaScript it is perfectly permissible to have properties with numeric values, numeric first letters and symbols and spaces as characters, but then you must use the square bracket way of accessing properties.

改变样式属性的另一种有用方法是使用方括号访问该属性。这对于访问属性很有用,因为它们的名称如果正常表达会产生语法错误。在 JavaScript 中,完全允许属性带有数字值、数字首字母、符号和空格作为字符,但是您必须使用方括号方式访问属性。

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

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