You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

鼠标悬停图片触发文本显示后出现抖动问题求助

解决鼠标悬停图片时的抖动问题

这个抖动问题的根源很清晰:当你把鼠标移到显示出来的「Watch/play」按钮上时,鼠标实际上离开了<img>元素,触发了onmouseout事件,导致按钮隐藏;紧接着鼠标又回到了图片区域,触发onmouseover让按钮重新显示——如此循环往复,就产生了抖动效果。

下面给你两种简单有效的解决方案:

方案一:用CSS伪类替代JS事件(更简洁稳定)

完全不需要JavaScript,通过父元素<a>:hover状态来统一控制按钮显示/隐藏和图片切换,整个<a>区域都是触发范围,鼠标移到按钮上也不会触发移出事件。

修改后的代码如下:

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#'>
  <img class="streamer_img" alt="example" src="https://placeimg.com/640/480/nature" />
  <p class="btn" id="hiddentext">Watch/play</p>
</a>

CSS

.btn {
  margin-top: -90px;
  z-index: 999999999;
  position: absolute;
  text-align: center;
  background: #37a000;
  display: none; /* 默认隐藏 */
}

/* 父元素hover时显示按钮 */
a:hover .btn {
  display: block;
}

/* 父元素hover时切换图片 */
a:hover .streamer_img {
  content: url('https://placeimg.com/640/480/people');
}

这种方式更符合前端开发的最佳实践,代码简洁且避免了JS事件可能带来的额外问题。

方案二:调整JS事件绑定到父元素

如果一定要保留原有的JavaScript逻辑,你可以把onmouseoveronmouseout事件绑定到父元素<a>上,而不是<img>,这样鼠标在按钮上时仍然处于父元素的hover范围内,不会触发移出事件。

修改后的HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' 
   onmouseover="document.querySelector('.streamer_img').src='https://placeimg.com/640/480/people'; displayText('hiddentext')" 
   onmouseout="document.querySelector('.streamer_img').src='https://placeimg.com/640/480/nature'; hideText('hiddentext')">
  <img class="streamer_img" alt="example" src="https://placeimg.com/640/480/nature" />
  <p class="btn" id="hiddentext" style="display: none;">Watch/play</p>
</a>

JS和CSS保持不变即可,这样也能解决抖动问题,因为事件的触发范围变成了整个<a>容器。

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

火山引擎 最新活动