<style>
.box {
width: 100px;
height: 100px;
border: 1px solid;
transition: background-color 0.3s ease; /* 添加过渡效果 */
}
. {
background: deepskyblue;
}
</style>
<div class="container">
<div class="box"></div>
<button >切换</button>
</div>
<script>
let btn = ("btn");
let box = ('.box')
let active = false
<!--给按钮添加事件-->
("click", () => {
// 直接修改style样式
= active ? "transparent" : "yellow"
// 通过添加class,控制显示
if (!active) {
("active")
} else {
("active")
}
// 通过设置className 控制样式
if (!active) {
= 'box active';
} else {
= 'box';
}
// 通过setAttribute,设置元素属性
if (!active) {
("class", "box active");
} else {
("class", "box");
}
active = !active // 状态取反
// 如果元素已经包含了指定的类,则会移除该类;如果元素没有包含指定的类,则会添加该类。
('active');
})
// 鼠标的事件
// click:鼠标单击事件,当鼠标在元素上单击时触发。
// dblclick:鼠标双击事件,当鼠标在元素上双击时触发。
// mousedown:鼠标按下事件,当鼠标在元素上按下任意按钮时触发。
// mouseup:鼠标松开事件,当鼠标在元素上松开按钮时触发。
// mousemove:鼠标移动事件,当鼠标在元素上移动时触发。
// mouseover:鼠标移入事件,当鼠标移动到元素上方时触发。
// mouseout:鼠标移出事件,当鼠标从元素上方移出时触发。
// contextmenu:鼠标右键事件,当用户在元素上点击鼠标右键时触发。
// wheel:鼠标滚轮事件,当用户使用鼠标滚轮时触发。
// 可以通过 addEventListener 方法来为元素添加事件监听器
// 鼠标移入,移出
("mouseover", () => {
= `0px 0px 4px 2px red`
})
("mouseleave", () => {
= `none`
})
</script>