You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中为容器div绑定悬停切换图片效果并迁移至外部JS文件

鼠标悬停切换图片:内联事件迁移到外部JS的解决方案

第一步:清理HTML中的内联事件

先把sayHi类div标签上的onmouseover和onmouseout属性删掉,让HTML结构更简洁:

<div class="sayHi">
  <!-- 这里保留你的"Say Hi"文本和图片元素 -->
  <img src="original-image.jpg" alt="描述文本">
  <span>Say Hi</span>
</div>

第二步:外部JS文件中绑定事件

核心注意点:必须等页面DOM加载完成后再获取元素绑定事件,否则会出现找不到元素的问题,下面是两种可行写法:

写法一:监听DOM加载完成事件(通用推荐)

这种写法不管JS文件放在页面哪个位置都能正常工作:

// 等待DOM全部渲染完毕再执行
document.addEventListener('DOMContentLoaded', function() {
  // 获取目标容器
  const sayHiBox = document.querySelector('.sayHi');
  
  // 悬停时切换图片
  function switchToHoverImg() {
    const targetImg = sayHiBox.querySelector('img');
    targetImg.src = '你的悬停图片路径'; // 替换成实际图片地址
  }
  
  // 鼠标离开时恢复原图
  function switchToOriginalImg() {
    const targetImg = sayHiBox.querySelector('img');
    targetImg.src = '你的原始图片路径'; // 替换成实际图片地址
  }
  
  // 绑定鼠标事件
  sayHiBox.addEventListener('mouseover', switchToHoverImg);
  sayHiBox.addEventListener('mouseout', switchToOriginalImg);
});

写法二:JS文件放在页面底部(简化写法)

如果你的外部JS文件是放在</body>标签之前引入的(此时页面DOM已经加载完成),可以省略DOM加载监听,直接写:

const sayHiBox = document.querySelector('.sayHi');

sayHiBox.addEventListener('mouseover', function() {
  this.querySelector('img').src = '你的悬停图片路径';
});

sayHiBox.addEventListener('mouseout', function() {
  this.querySelector('img').src = '你的原始图片路径';
});

处理多个同类型容器的情况

如果页面上有多个sayHi类的容器,用querySelectorAll批量绑定事件:

document.addEventListener('DOMContentLoaded', function() {
  const allSayHiBoxes = document.querySelectorAll('.sayHi');
  
  allSayHiBoxes.forEach(box => {
    box.addEventListener('mouseover', function() {
      this.querySelector('img').src = '你的悬停图片路径';
    });
    box.addEventListener('mouseout', function() {
      this.querySelector('img').src = '你的原始图片路径';
    });
  });
});

内容的提问来源于stack exchange,提问作者istvan weisz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:01:03