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

如何用JavaScript实现鼠标悬停时隐藏图片并在同位置替换为文本

方案1:JavaScript实现(符合需求要求)

第一步:修正现有代码的基础问题

你现有代码的父级div没有设置相对定位,会导致文本的绝对定位位置偏差,先调整HTML和CSS:
修正后的CSS:

/* 给父容器加专属样式 */
.img-container {
  position: relative;
  width: 600px;
  height: 400px;
  margin-top: 80px;
}
.main-img1{
  height: 100%;
  width: 100%;
  background-size: cover;
  box-shadow: 10px 10px 5px rgb(24, 22, 22);
  border-radius: 50px;
  display: block;
}
.img1-text{
  display: none;
  position: absolute;
  /* 居中定位,可按需调整位置 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  font-size: 25px;
  color: black;
  margin: 0;
}

修正后的HTML:

<section class="main-body">
  <!-- 给父div加专属类名 -->
  <div class="img-container">
    <img class="main-img1" src="img/automotive.jpg" alt="汽车摄影">
    <h1 class="img1-text" id="img1text">这里是我的部分汽车摄影作品!我擅长“追焦拍摄”,也就是在车辆移动时进行拍摄,让背景和前景呈现出动感效果。</h1>
  </div>
</section>

第二步:添加JS交互逻辑

在页面</body>标签前插入script标签,写入以下代码即可:

// 获取对应DOM元素
const imgContainer = document.querySelector('.img-container');
const showImg = document.querySelector('.main-img1');
const showText = document.querySelector('.img1-text');

// 鼠标移入父容器时切换显示状态
imgContainer.addEventListener('mouseenter', () => {
  showImg.style.display = 'none';
  showText.style.display = 'block';
})

// 鼠标移出父容器时恢复显示状态
imgContainer.addEventListener('mouseleave', () => {
  showImg.style.display = 'block';
  showText.style.display = 'none';
})

方案2:纯CSS实现(无JS更简洁,可按需选用)

如果没有强制要求必须用JS实现,只需要在CSS中追加两行代码即可完成效果,不需要编写任何JS逻辑,性能更稳定:

/* 父容器悬停时隐藏图片 */
.img-container:hover .main-img1 {
  display: none;
}
/* 父容器悬停时显示文本 */
.img-container:hover .img1-text {
  display: block;
}

内容的提问来源于stack exchange,提问作者Nick Thompson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:27:01