这段代码实现了一个简单的图片切换效果。当用户将鼠标悬停在不同的小缩略图上时,主显示框(#box
)的背景图片会切换为相应的缩略图所代表的图片。
实现效果:
代码:
<!DOCTYPE html>
<html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>图片切换示例2</title><style>* {padding: 0;margin: 0;}#box {border: 1px solid #ccc;width: 400px;height: 400px;background: url('./image/image1.jpg') no-repeat center center;background-size: cover;}img {width: 30px;height: 30px;}#box ul {list-style: none;}#box ul li {display: inline-block;margin-right: 10px;cursor: pointer;/* 添加光标样式 */}</style></head><body><div id="box"><ul><li data-img="url('./image/image1.jpg')"><img src="./image/image1.jpg" alt="图片1"></li><li data-img="url('./image/image2.jpg')"><img src="./image/image2.jpg" alt="图片2"></li><li data-img="url('./image/image3.jpg')"><img src="./image/image3.jpg" alt="图片3"></li><li data-img="url('./image/image4.jpg')"><img src="./image/image4.jpg" alt="图片4"></li><li data-img="url('./image/image5.jpg')"><img src="./image/image5.jpg" alt="图片5"></li></ul></div><script>document.querySelectorAll('#box ul li').forEach(li => {li.addEventListener('mouseover', function() {const imgSrc = this.getAttribute('data-img');document.getElementById('box').style.background = `${imgSrc} no-repeat center center`;document.getElementById('box').style.backgroundSize = 'cover';});});</script></body>
</html>
部分代码解析:
1. data-*
属性
javascript">data-img="url('./image/image1.jpg')"
使用 data-*
属性:将图片路径存储在 data-img
属性中,这样可以减少对每个 li
的 JavaScript 调用,提高可读性和可维护性。
2. js代码解析
javascript">document.querySelectorAll('#box ul li').forEach(li => {li.addEventListener('mouseover', function() {const imgSrc = this.getAttribute('data-img');document.getElementById('box').style.background = `${imgSrc} no-repeat center center`;document.getElementById('box').style.backgroundSize = 'cover';});});
2.1 选择元素:
javascript">document.querySelectorAll('#box ul li')
这行代码选取了所有在 #box
元素下的 ul
列表中的 li
项。
2.2 遍历每个 li
元素:
javascript">.forEach(li => {
对选中的每个 li
元素执行后面的函数。
2.3 添加事件监听:
javascript">li.addEventListener('mouseover', function() {
为每个 li
元素添加一个鼠标悬停(mouseover)事件的监听器。当鼠标悬停在某个 li
元素上时,执行这个函数。
2.4 获取图片源:
javascript">const imgSrc = this.getAttribute('data-img');
在事件处理函数中,使用 this
关键字指向当前悬停的 li
元素,并获取它的 data-img
属性值,赋值给 imgSrc
。
2.5 改变背景:
javascript">document.getElementById('box').style.background = `${imgSrc} no-repeat center center`;
document.getElementById('box').style.backgroundSize = 'cover';
将 #box
元素的背景设置为 imgSrc
指定的图片,设置为不重复(no-repeat),居中(center center),并且通过 backgroundSize
设置为覆盖(cover)。