How to remove CSS properties using JavaScript?

Method 1: Using CSS removeProperty: The CSSStyleDeclaration.removeProperty() method is used to remove a property from an element's style.
You can choose the style of an element by looping through styleSheetsthe array and selecting cssRule. You can then specify the method using the properties to be removed removeProperty.

syntax:

element.removeProperty('property')

Case:

<!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>

Rendering:

Insert image description here
Method 2: Usage setPropertymethod: The CSSStyleDeclaration.setProperty() method can be used to set the desired properties of the style. Select the element whose attribute must be removed and apply this attribute to its style attribute. Setting this property initialto resets the property to its initial value, eliminating any effect of the property.

syntax:

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

Case:

<!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>

Rendering:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45959525/article/details/119885124