为什么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>
问题是您在DOM更新之前立即进行所有这些更改。而是考虑将样式属性实际设置为空,请参见here
div.setAttribute("style","");
只需在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)
}
这看起来非常像Chrome JS优化错误。尽管HTML5规范说]
样式IDL属性必须返回CSSStyleDeclaration,其值表示在属性中指定的声明(如果存在)。突变CSSStyleDeclaration对象必须创建样式属性在元素上(如果还没有),然后更改其值代表序列化形式的值CSSStyleDeclaration对象。每个对象必须返回相同的对象时间。
Chrome正在尝试尽可能长时间地延迟样式属性的创建,以便可以将IDL属性的一系列变异汇总为单个content属性的创建/更改。该代码只是省略了在removeAttribute调用之前执行create / change操作,但对于getAttribute则正确执行了此操作。一旦创建了content属性,removeAttribute将成功销毁它。
作为advised on MDN,应将removeAttribute设置为null或空字符串。
尽管可能无法正常工作,并且解决方案是使用requestAnimationFrame或setInterval,如果要定位的次标准浏览器不支持RAF。
似乎需要更多时间,example
function DelStyle() {
var div = document.getElementById("myDiv");
console.log(div)
div.style.border = 'solid #3B3B3D 1px';
console.log(div)
setTimeout((function(div) {
return function() {
div.removeAttribute("style");
console.log(div);
}
})(div), 500);
}
半秒钟后我要移除属性。
[我在调用setAttribute()
之前尝试同时调用getAttribute()
和removeAttribute()
方法。
对我来说不起作用:将style属性设置为空也没有。
起作用的是使用removeAttributeNode()
方法。
如此处所述:http://www.w3schools.com/jsref/met_element_removeattributenode.asp结果将是相同的;例如
function DelStyle() { var div = document.getElementById("myDiv"); console.log(div) div.style.border = 'solid #3B3B3D 1px'; console.log(div) div.removeAttributeNode(div.getAttribute("style")); console.log(div) }
测试此
div.attributes.removeNamedItem("style");
我在使用removeProperty和removeAttribute时遇到麻烦。我通过在我的html中而不是css中编写该属性/属性的原始实例来解决此问题。