<div id='bigBox'>
  <div class='smallBox'>
    <div class='text'>文字</div>
    <div class='image'>
      <img src='image1.jpg' alt='图片1'>
      <img src='image1_hover.jpg' alt='图片1(滑过)'>
    </div>
  </div>
  <div class='smallBox'>
    <div class='text'>文字</div>
    <div class='image'>
      <img src='image2.jpg' alt='图片2'>
      <img src='image2_hover.jpg' alt='图片2(滑过)'>
    </div>
  </div>
  <div class='smallBox'>
    <div class='text'>文字</div>
    <div class='image'>
      <img src='image3.jpg' alt='图片3'>
      <img src='image3_hover.jpg' alt='图片3(滑过)'>
    </div>
  </div>
</div>
<script>
// 获取大盒子和小盒子们
const bigBox = document.getElementById('bigBox');
const smallBoxes = bigBox.querySelectorAll('.smallBox');

// 遍历每个小盒子
smallBoxes.forEach((smallBox) => {
  const text = smallBox.querySelector('.text');
  const images = smallBox.querySelectorAll('.image img');

  // 添加鼠标滑过事件监听器
smallBox.addEventListener('mouseover', () => {
    // 添加样式
smallBox.classList.add('active');

    // 切换图片
images[0].style.display = 'none';
images[1].style.display = 'block';
  });

  // 添加鼠标离开事件监听器
smallBox.addEventListener('mouseout', () => {
    // 移除样式
smallBox.classList.remove('active');

    // 切换图片
images[0].style.display = 'block';
images[1].style.display = 'none';
  });
});
</script>
<style>
/* 默认样式 */
.smallBox {
  width: 200px;
  height: 200px;
  border: 1px solid black;
}

.smallBox .text {
  text-align: center;
  line-height: 200px;
}

.smallBox .image img {
  display: block;
  width: 100%;
  height: 100%;
}

/* 鼠标滑过样式 */
.smallBox.active {
  border-color: red;
}

.smallBox.active .image img:first-child {
  display: none;
}

.smallBox.active .image img:last-child {
  display: block;
}
</style>
原生JS实现鼠标悬停切换图片和样式效果

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

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