给当前元素添加类样式
Element.classList.add("类名");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
.red {
color: red;
}
</style>
</head>
<body>
<div id="username">Peter</div>
<button id="change">改变样式</button>
<script>
document.querySelector("#change").onclick = function()
{
document.querySelector("#username").classList.add("red");
}
</script>
</body>
</html>
给当前元素移除类样式
Element.classList.remove("类名");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
.red {
color: red;
}
</style>
</head>
<body>
<div id="username" class="red">Peter</div>
<button id="change">改变样式</button>
<script>
document.querySelector("#change").onclick = function()
{
document.querySelector("#username").classList.remove("red");
}
</script>
</body>
</html>
检测当前元素添是否包含类样式
Element.classList.contains("类名");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
.red {
color: red;
}
.blue {
color: blue;
}
</style>
</head>
<body>
<div id="username" class="red">Peter</div>
<button id="change">改变样式</button>
<script>
var selector = document.querySelector("#username");
document.querySelector("#change").onclick = function()
{
if (selector.classList.contains("red")) {
selector.classList.remove("red");
selector.classList.add("blue");
}
}
</script>
</body>
</html>
给当前元素切换类样式:有就删除,没有就添加
Element.classList.toggle("类名");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
.red {
color: red;
}
</style>
</head>
<body>
<div id="username" class="red">Peter</div>
<button id="change">改变样式</button>
<script>
document.querySelector("#change").onclick = function()
{
document.querySelector("#username").classList.toggle("red");
}
</script>
</body>
</html>
网友评论