JavaScript 如何移除CSS属性
方法1:使用CSS removeProperty
CSStyleDeclaration.removeProperty() 方法用于从元素的样式中移除属性。通过遍历styleSheets数组并选择cssRule来选择元素的样式。然后可以使用removeProperty方法指定要删除的属性。
语法:
element.removeProperty('property')
示例1:
<!DOCTYPE html>
<html>
<head>
<title>
How to remove CSS property using JavaScript?
</title>
<style>
.elem {
color: green;
font-size: 3rem;
text-decoration: underline;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to remove CSS property using JavaScript?
</b>
<div class="elem">Hello World!</div>
<p>
Click on the button below to remove
the text decoration of the element
</p>
<button onclick="removeProperty()">
Remove text-decoration property
</button>
<script>
function removeProperty() {
element =
document.styleSheets[0].cssRules[0].style;
element.removeProperty('text-decoration');
}
</script>
输出:
方法2:使用setProperty 方法
CSSStyleDeclaration.setProperty() 方法可以用来设置样式的所需属性。选择要删除属性的元素,并将该属性应用于其样式属性。将该属性设置为 ‘initial’ 可将属性重置为其初始值,从而去除任何属性的影响。
语法:
element.style.setProperty('color', 'initial')
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to remove CSS property using JavaScript?
</title>
<style>
.elem {
color: green;
font-size: 3rem;
text-decoration: underline;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to remove CSS property using JavaScript?
</b>
<div class="elem">Hello World!</div>
<p>
Click on the button below to remove the text
color of the element
</p>
<button onclick="removeProperty()">
Remove color property
</button>
<script>
function removeProperty() {
element = document.querySelector('.elem');
element.style.setProperty('color', 'initial');
}
</script>
</body>
</html>
输出: