求助:鼠标悬停图片时跟随按钮出现异常闪烁问题
解决鼠标悬停图片时按钮闪烁的问题
需求与问题
需求:鼠标悬停在图片上时,在光标上方显示一个可点击按钮。
当前实现遇到的问题:按钮出现不必要的闪烁效果。尝试给按钮添加pointer-events: none属性,虽然能解决闪烁,但会同时禁用按钮的onclick事件。
闪烁原因
按钮显示后,鼠标会进入按钮区域,触发图片的onmouseout事件,导致按钮隐藏;随后鼠标回到图片上,又触发onmousemove显示按钮,如此循环往复就造成了闪烁。
解决方案
方法一:将鼠标事件绑定到父容器
把onmousemove和onmouseleave事件从图片移到父容器上,这样鼠标移到按钮上时,不会触发容器的mouseleave,避免按钮反复显示隐藏。
修改后的完整代码:
HTML
<!-- bootstrap --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <div id="maindiv" onmousemove="movebox(event)" onmouseleave="removebox()"> <img src="https://images.unsplash.com/photo-1563884993747-a52423c68196?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1374&q=80" /> <button id="box" class="btn btn-primary" onclick="clickBtn()">click</button> </div>
JavaScript
const box = document.getElementById("box"); function movebox(e) { box.style.left = e.clientX - 20 + 'px'; box.style.top = e.clientY - 20 + 'px'; box.style.display = 'block'; } function removebox() { box.style.display = 'none'; } function clickBtn() { console.log("clicked") }
CSS
#maindiv { border: 1px solid blue; padding: 1px; display: flex; justify-content: center; text-align: center; align-items: center; min-height: 100vh; } #maindiv img { max-width: 400px; max-height: 400px; object-fit: scale-down; border: 1px solid red; } #box { position: absolute; z-index: 100; display: none; }
额外优化:把点击函数名从click改为clickBtn,避免和浏览器内置的click函数冲突。
方法二:用pointer-events: none+父容器点击判断
如果不想修改事件绑定的元素,可以给按钮添加pointer-events: none让鼠标事件透传,同时在父容器上监听点击,判断点击位置是否在按钮区域内,触发点击逻辑:
修改CSS:
#box { position: absolute; z-index: 100; display: none; pointer-events: none; }
添加JavaScript:
document.getElementById('maindiv').addEventListener('click', function(e) { const rect = box.getBoundingClientRect(); if (e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom) { console.log("clicked"); } });
这样既解决了闪烁,又能实现按钮的点击效果。
内容的提问来源于stack exchange,提问作者Josal
相关产品推荐
相关产品推荐

