方法一:
使用 CSSremoveProperty:CSSStyleDeclaration.removeProperty() 方法用于从小部件的样式中删除属性。
可以通过迭代 styleSheets 字段并选择 cssRule 来选择元素的样式。 然后可以使用要删除的属性来指定removeProperty 技术。
复杂句子:
element.removeProperty('property')
示例1:
<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>
</body>
</html>
输出:
在点击按钮之前:
单击按钮后:
方式2:使用setProperty方法:CSSStyleDeclaration.setProperty()方法可用于设置样式所需的属性。 选择必须去除其属性的元素并将该属性应用于其样式属性。 将此属性设置为“初始”会将该属性重置为其初始值,从而清除该属性的任何影响。
复杂句子:
element.style.setProperty('color','initial')
例如:
<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>
输出:
单击按钮后:
这篇文章就结束了~