0
点赞
收藏
分享

微信扫一扫

【开发小技巧】01-如何使用JavaScript删除CSS属性?

小桥流水2016 2022-09-28 阅读 145

【开发小技巧】01-如何使用JavaScript删除CSS属性?_javascript

句法:

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>
</body>

</html>

输出:

在单击按钮之前:

【开发小技巧】01-如何使用JavaScript删除CSS属性?_css_02


单击按钮后:

【开发小技巧】01-如何使用JavaScript删除CSS属性?_javascript_03

方法2:使用setProperty方法:该CSSStyleDeclaration.setProperty()方法可用于设置的样式的所需的属性。选择必须删除其属性的元素,并将此属性应用于其style属性。将此属性设置为“ 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>

输出:

  • 在单击按钮之前:

【开发小技巧】01-如何使用JavaScript删除CSS属性?_css_04

单击按钮后:

【开发小技巧】01-如何使用JavaScript删除CSS属性?_html_05

本文完~


【开发小技巧】01-如何使用JavaScript删除CSS属性?_css_06

【开发小技巧】01-如何使用JavaScript删除CSS属性?_css_07

举报

相关推荐

0 条评论