如何使用JavaScript删除CSS属性?

方法1:使用cssremoveProperty:该CSSStyleDeclaration.removeProperty()方法被用来从一个元件的样式删除一个属性。
通过遍历styleSheets数组并选择cssRule,可以选择元素的样式。然后可以使用要删除的属性指定removeProperty方法。

句法:

element.removeProperty('property')

案例:

<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<style>
			.elem {
				color: green;
				font-size: 3rem;
				text-decoration: underline;
			}
		</style>
	</head>
	<body>
		<div class="elem">Hello World!</div>
		<button onclick="removeProperty()">删除文字修饰属性</button>
		<script>
			function removeProperty() {
				element = document.styleSheets[0].cssRules[0].style;
				element.removeProperty('text-decoration');
			}
		</script>
	</body>
</html>

效果图:

在这里插入图片描述
方法2:使用setProperty方法:该CSSStyleDeclaration.setProperty()方法可用于设置的样式的所需的属性。选择必须删除其属性的元素,并将此属性应用于其style属性。将此属性设置为initial可将属性重置为其初始值,从而消除该属性的任何影响。

句法:

element.style.setProperty('color''initial'

案例:

<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<style>
			.elem {
				color: green;
				font-size: 3rem;
				text-decoration: underline;
			}
		</style>
	</head>
	<body>
		<div class="elem">Hello World!</div>
		<button onclick="removeProperty()">删除属性颜色</button>
		<script>
			function removeProperty() {
				element = document.querySelector('.elem');
				element.style.setProperty('color', 'initial');
			}
		</script>
	</body>
</html>

效果图:
在这里插入图片描述

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值