鼠标悬停时#newdot元素闪烁及Firefox消失问题求助
解决鼠标跟随元素在Chrome闪烁、Firefox消失的问题
我一眼就看出问题所在了——你的#newdot元素z-index比#backgroundiv高,而且是绝对定位,当它跟着鼠标移动时,会挡住鼠标和#backgroundiv的交互:鼠标实际悬停在#newdot上,而不是#backgroundiv,这就会触发hover的离开回调,导致元素隐藏;紧接着鼠标又回到#backgroundiv上,元素又显示,循环往复就造成了闪烁,Firefox对这种事件触发更敏感,直接就会让元素消失。
下面是修复后的完整方案:
核心修复点
- 给
#newdot添加pointer-events: none,让它不捕获任何鼠标事件,鼠标操作会直接穿透到下层的#backgroundiv - 把
#backgroundiv设为position: relative,让#newdot的绝对定位相对于它,这样计算鼠标位置更准确,也避免滚动时的偏移 - 调整鼠标位置计算逻辑,用
e.offsetX/e.offsetY(相对于父元素的坐标)替代e.pageX/e.pageY(相对于文档的坐标)
修改后的完整代码
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="backgroundiv"> <div id="newdot" class="hide"></div> </div>
(把#newdot放到#backgroundiv内部,配合relative定位更合理)
CSS
#backgroundiv { width: 400px; height: 400px; background-color: blue; z-index: 1; position: relative; /* 新增,让子元素绝对定位相对于它 */ } #newdot { width: 40px; height: 40px; background-color: red; position: absolute; z-index: 2; pointer-events: none; /* 核心修复,不捕获鼠标事件 */ } .hide { display: none; }
JavaScript
$(document).ready(function() { $("#backgroundiv") .hover(function() { $("#newdot").removeClass("hide"); }, function() { $("#newdot").addClass("hide"); }) .on('mousemove', function(e) { // 用offsetX/offsetY计算相对于backgroundiv的位置,再减去自身一半宽度居中 const dotHalfWidth = $("#newdot").width() / 2; $('#newdot').css({ left: e.offsetX - dotHalfWidth, top: e.offsetY - dotHalfWidth }); }); });
为什么这样改能解决问题?
pointer-events: none让#newdot变成了“透明”的鼠标目标,不管它怎么移动,鼠标始终和#backgroundiv保持交互,不会触发离开事件- 把
#newdot放到#backgroundiv内部并设置父元素为relative,确保元素只会在#backgroundiv范围内移动,不会跑到外面去 offsetX/offsetY是相对于父元素的坐标,比pageX/pageY更适合这种相对定位的场景,滚动页面时也不会出现位置偏移
这样修改后,Chrome和Firefox里都能稳定运行,不会再出现闪烁或消失的问题了。
内容的提问来源于stack exchange,提问作者bevan7
相关产品推荐
相关产品推荐

