方法一:
<style>
li {
width: 100px;
height: 100px;
background: url(./img/1.jpg) no-repeat;
float: left;
list-style: none;
margin-left: 50px;
}
li.on {
background: url(./img/2.jpg) no-repeat;
}
</style>
方法一、
技术点:多个开关控制多个按钮 所以需要for循环
<body>
<div>
<li></li>
<li></li>
<li></li>
</div>
<script>
var img = document.querySelectorAll("li");
for (let i = 0; i < img.length; i++) {
img[i].kg = true;
img[i].onclick = function(){
if (this.kg) {
img[i].className = "on"
} else{
img[i].className = ""
}
this.kg = !this.kg;
}
}
</script>
方法二:
for (let i = 0; i < img.length; i++) {
img[i].onclick = function(){
this.classList.toggle("on")
}
}