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

鼠标悬停lightblue div显示文本时出现闪烁,如何解决?

解决鼠标悬停文本闪烁问题

问题原因

文本是绝对定位在.lightblue元素上方的,当鼠标移到文本上时,会触发.lightblue的mouseleave事件,文本开始淡出;而文本淡出过程中鼠标又会重新落在.lightblue上,触发mouseenter让文本淡入,反复交替就导致了闪烁。

解决方案

方法1:将文本元素放入.lightblue容器内

把.text放到.lightblue内部,这样鼠标在文本上时仍处于.lightblue的范围内,不会触发mouseleave。

修改后的HTML:

<div class="lightblue">
  <div class="text">This text should not<br>blink on hover</div>
</div>

调整CSS:

.lightblue{
  width:50%;
  background:lightblue;
  float:right;
  height:50vh;
  position: relative; /* 让内部绝对定位的文本相对于容器定位 */
}
.text{
  display:none;
  color:#000;
  position:absolute;
  text-align:right;
  top:25px;
  right:25px;
  font-size:24px;
}

jQuery代码无需修改。

方法2:给文本添加pointer-events: none

让文本元素不接收鼠标事件,鼠标移到文本上时,事件会穿透到下方的.lightblue元素,避免触发mouseleave。

修改CSS:

.text{
  display:none;
  color:#000;
  position:absolute;
  text-align:right;
  top:25px;
  right:25px;
  font-size:24px;
  pointer-events: none; /* 禁止文本接收鼠标事件 */
}

此方法无需改动HTML和jQuery,适合文本不需要交互的场景。

方法3:用父容器包裹两个元素,监听父容器的鼠标事件

创建父容器包裹.lightblue和.text,监听父容器的鼠标事件,确保鼠标在任意子元素上都不会离开父容器范围。

修改后的HTML:

<div class="container">
  <div class="lightblue"></div>
  <div class="text">This text should not<br>blink on hover</div>
</div>

调整CSS:

.container{
  width:50%;
  float:right;
  position: relative;
}
.lightblue{
  width:100%;
  background:lightblue;
  height:50vh;
}
.text{
  display:none;
  color:#000;
  position:absolute;
  text-align:right;
  top:25px;
  right:25px;
  font-size:24px;
}

修改jQuery:

$('.container').mouseenter(
  function() {
      $('.text').fadeIn(200) 
  }),

$('.container').mouseleave(
  function() {
      $('.text').fadeOut(200);
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:45:51