body中有一个id为mask的span标签,里面是所有图片的src地址,每张图片都有自己的id,从img1到img10,还有一个id为show的div标签,里面是第一张图片,图片id为simg,在script中写出js代码,实现鼠标点击图片,show里的背景图片相应的切换为被点击的图片,写出完整代码
时间: 2023-11-25 08:06:30 浏览: 75
HTML代码:
```
<body>
<div id="show" style="background-image: url('img1.jpg');"></div>
<span id="mask">
<img id="img1" src="img1.jpg">
<img id="img2" src="img2.jpg">
<img id="img3" src="img3.jpg">
<img id="img4" src="img4.jpg">
<img id="img5" src="img5.jpg">
<img id="img6" src="img6.jpg">
<img id="img7" src="img7.jpg">
<img id="img8" src="img8.jpg">
<img id="img9" src="img9.jpg">
<img id="img10" src="img10.jpg">
</span>
</body>
```
JS代码:
```
var mask = document.getElementById("mask");
var imgs = mask.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = function() {
var src = this.getAttribute("src");
var id = this.getAttribute("id");
var show = document.getElementById("show");
show.style.backgroundImage = "url(" + src + ")";
show.style.backgroundSize = "cover";
show.style.backgroundPosition = "center";
show.style.backgroundRepeat = "no-repeat";
show.setAttribute("data-id", id);
}
}
var show = document.getElementById("show");
show.style.backgroundSize = "cover";
show.style.backgroundPosition = "center";
show.style.backgroundRepeat = "no-repeat";
var simg = document.getElementById("simg");
show.setAttribute("data-id", "img1");
```
阅读全文