.container {
  display: flex;
}

.box {
  width: 100px;
  height: 100px;
  background-color: gray;
  margin-right: 10px;
}

.image-container {
  width: 200px;
  height: 200px;
  background-color: lightgray;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-container img {
  display: none;
}

.image-container img.active {
  display: block;
}
var boxes = document.querySelectorAll('.box');
var images = document.querySelectorAll('.image-container img');

// 默认第一个小盒子和对应的第一张图片为选中状态
boxes[0].classList.add('active');
images[0].classList.add('active');

// 监听鼠标滑动事件
boxes.forEach(function(box, index) {
  box.addEventListener('mouseover', function() {
    // 移除所有小盒子和图片的选中状态
    boxes.forEach(function(box) {
      box.classList.remove('active');
    });
    images.forEach(function(image) {
      image.classList.remove('active');
    });
    
    // 给当前滑动的小盒子和对应的图片添加选中状态
    box.classList.add('active');
    images[index].classList.add('active');
  });
});

通过以上代码,当鼠标滑动到左边的小盒子上时,右边的图片会随之改变,并且每个小盒子可以设置不同的样式。

原生JS实现鼠标悬停切换图片效果

原文地址: http://www.cveoy.top/t/topic/fqcy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录