gpt4 book ai didi

javascript - element.style ="height: 90px;"和 element.style.height ="90px"有什么区别;?

转载 作者:太空宇宙 更新时间:2023-11-03 22:16:32 25 4
gpt4 key购买 nike

这两行之间有什么区别吗?

document.querySelector("div").style="height: 90px;"
document.querySelector("div").style.height="90px";

最佳答案

一个区别是,当您分配给 .style 时属性,您将覆盖分配给 .style 的任何使用属性(property),如果有的话:

// this next assignment will be immediately overwritten!
document.querySelector("div").style = 'background-color: yellow';
document.querySelector("div").style = "height: 90px;"
div {
background-color: green;
}
<div>
x
</div>

// Not overwritten anymore!
document.querySelector("div").style.backgroundColor = 'yellow';
document.querySelector("div").style.height = "90px";
div {
background-color: green;
}
<div>
x
</div>

另一个问题是 style对象应该是只读的,尽管流行的网络浏览器allow it .参见 MDN :

Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only. Instead, styles can be set by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...') as using elt.style.cssText = '...' or elt.setAttribute('style', '...') sets the complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style using elt.style.<property> (i.e., elt.style.fontSize, not elt.style.font-size).

分配给它不是一个好主意。为了更好的兼容性,分配给 .style.cssText (或者只分配给一个特定的属性,比如 .height ):

document.querySelector("div").style.cssText = "height: 90px;"
div {
background-color: green;
}
<div>
x
</div>

关于javascript - element.style ="height: 90px;"和 element.style.height ="90px"有什么区别;?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56543271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com