请问一下怎么实现一个DIV的背景图片来回切换?
问题描述:
我想做一个文件树,有两张图片用来做一个DIV的背景。我想当点击这个DIV时可以实现切换这两张图片。
答
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 600px;
height: 400px;
background: url(1.jpg);
}
</style>
</head>
<body>
<div></div>
<button>切换</button>
<script>
btn = document.querySelector("button");
div = document.querySelector("div");
flag = true;
btn.onclick = function() {
if(flag) {
div.style.background = "url(2.jpg)";
flag = false;
}else {
div.style.background = "url(1.jpg)";
flag = true;
}
}
</script>
</body>
</html>
方法可以有很多,也可以将 If 判断的条件换为之前的 url,如果匹配就换另一个。
答
点击事件,用js直接改变背景图,或者写好不同状态的样式背景图,改变类名都是一样的