javascript怎么删除类名

javascriptjavascript 2023-08-29 17:32:11 608
摘要: 在javascript中,可以利用classList属性和remove()方法来删除类名classList属性返回元素的类名,作为DOMTokenList对象。该属性用于在元素中添加,移除及切换CSS类。classList属性是只读的,但你可以使用add()和remo...

在javascript中,可以利用classList属性和remove()方法来删除类名

classList 属性返回元素的类名,作为 DOMTokenList 对象。该属性用于在元素中添加,移除及切换 CSS 类。

classList 属性是只读的,但你可以使用 add() 和 remove() 方法修改它。

示例:删除类名“mystyle”

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">

		<style>
			.mystyle {
				width: 300px;
				height: 50px;
				background-color: coral;
				color: white;
				font-size: 25px;
			}
		</style>
	</head>
	<body>

		<p>点击按钮移除 DIV 元素中的 "mystyle" 类.</p>
		<button onclick="myFunction()">点我</button><br><br>
		<div id="myDIV" class="mystyle">
			我是一个 DIV 元素。
		</div>
		<script>
			function myFunction() {
				var div=document.getElementById("myDIV");
				div.classList.remove("mystyle");
			}
		</script>

	</body>
</html>

1.gif

【相关推荐:javascript学习教程