<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
:root {
--bg: #638ac5;
--bg_1:#ff3161;
}
.hard {
width: 90px;
height: 200px;
background: var(--bg);
transition: 0.5s;
}
.cor {
background:var(--bg_1);
}
</style>
</head>
<body>
<div class="hard">点击改变背景颜色</div>
<script>
let hard = document.querySelector(".hard");
//hard 点击时触发
hard.onclick = function() {
//.classList.toggle(class) 类名存在就消除 不存在就添加class
hard.classList.toggle('cor');
}
</script>
</body>
</html>
js 点击添加和去除类名 element.classList.toggle(‘class‘)
于 2022-11-17 10:42:47 首次发布