gpt4 book ai didi

javascript - removeAttribute() 对 DOM 不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:09:39 24 4
gpt4 key购买 nike

为什么 removeAttribute() 不删除以下代码中的任何内容:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="myDiv">
Element with style.
</div>
<br />
<br />
<button onclick="DelStyle()">
Remove the style attribute from the element
</button>
<script type="text/javascript">
function DelStyle() {
var div = document.getElementById("myDiv");
console.log(div)
div.style.border = 'solid #3B3B3D 1px';
console.log(div)
div.removeAttribute("style");
console.log(div)
}
</script>
</body>
</html>

最佳答案

只需在 removeAttribute("style") 之前调用 getAttribute("style")。

例如

    function DelStyle() {
var div = document.getElementById("myDiv");
console.log(div)
div.style.border = 'solid #3B3B3D 1px';
console.log(div)
div.getAttribute("style");
div.removeAttribute("style");
console.log(div)
}

参见 http://jsfiddle.net/qTv22/

这看起来很像 Chrome JS 优化错误。尽管 HTML5 规范说

The style IDL attribute must return a CSSStyleDeclaration whose value represents the declarations specified in the attribute, if present. Mutating the CSSStyleDeclaration object must create a style attribute on the element (if there isn't one already) and then change its value to be a value representing the serialized form of the CSSStyleDeclaration object. The same object must be returned each time.

Chrome 正试图尽可能地推迟样式属性的创建,以便 IDL 属性的一系列变化可以汇总到内容属性的单个创建/更改中。该代码只是省略了在 removeAttribute 调用之前执行创建/更改操作,但对 getAttribute 执行正确。创建内容属性后,removeAttribute 将成功销毁它。

关于javascript - removeAttribute() 对 DOM 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7165359/

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