使用javascript访问属性值的不同方法 [英] Different ways of accessing attribute values using javascript
问题描述
document.getElementById('myId').style;
是访问style属性的一种方法。
同样,
document.getElementById('myId')。getAttribute('style');
is one way of accessing the style attribute..
Also we can do the same using
document.getElementById('myId').getAttribute('style');
推荐答案
在第一个例子中,不能访问 style
属性,而是访问 style
属性。属性的值可以是任何东西,在 style
属性是一个对象的情况下。在第二个示例中,您正在访问标记的样式属性。属性的值只能是字符串。
In the first example you're not accessing to the style
attribute, but to the style
property. The property's value can be anything, in case of the style
property is an object. In the second example you're accessing to the style attribute of the tag. The attribute's value can be only string.
如果有一些属性,它们之间有一个映射。因此,如果在HTML节点上设置属性 style
,则会更新 style
属性,并应用您的样式。然而,这并不总是正确的:在一些版本的IE(至少直到IE7)的一个众所周知的错误是那种映射被打破,所以设置一个属性不会反映到属性。
In case of some attributes there is a mapping between them. So if you set an attribute style
on a HTML node, your style
property is updated and your style is applied. However, this is not always true: a well known bug in some versions of IE (at least till IE7) is that sort of mapping is broken, so set an attribute is not reflected to the property.
所以,如果你想在一个HTML节点上设置一个属性,你必须使用第二个。但是如果你想访问一个HTML节点的对象属性,你必须使用第一个。
So, if you want set an attribute on a HTML node, you have to use the second one. But if you want to access to the property of your object that represent a HTML node, you have to use the first one.
style
,强烈建议您使用第一个。
In case of the style
, the first one is strongly recommended.
):
document.body.style.border = "1px solid red";
console.log(document.body.style); // [object CSSStyleDeclaration]
console.log(document.body.getAttribute("style")); // "border: 1px solid red;"
这篇关于使用javascript访问属性值的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!