浏览器在动画/移动元素上未触发鼠标悬停/鼠标输入
如果您有一个具有移动动画的元素,则除非用户移动鼠标,否则不会触发 mouseover
和 mouseenter
事件。为了演示,请使用 jQuery 尝试下面的代码块。
如果您将鼠标放在移动的 div 前面,这样当 div 经过时您就不会移动鼠标,那么 mouseover
不会被触发,块也不会停止。
在 Firefox 中,无需手动将鼠标移动到 div 上,即可触发 mouseover
事件,但前提是您至少移动过一次鼠标。
我的问题是,是否有一种解决方法,以便在鼠标光标下移动的元素仍会触发其 mouseover
事件?
<script>
$(function() {
var move = 10,
left = 0,
width = 100;
var stop = setInterval(function() {
left += move;
$('#mydiv').css('left', left);
if (left < 0 || (left + width > parseInt($(window).width())))
move = -1 * move;
}, 10);
$('#mydiv').mouseover(function() { clearInterval(stop); });
});
</script>
<div id="mydiv" style="width: 100px; height: 100px; position: absolute; top: 0; left: 0; background-color: Black;"> </div>
我知道这个例子是人为的,但这只是为了证明这个问题。
If you have an element that has an animation to move it around, the mouseover
and mouseenter
events aren't fired unless the mouse is moved by the user. To demonstrate try the block of code below with jQuery.
If you put your mouse in front of the moving div so you're not moving the mouse when the div passes by then the mouseover
isn't fired and the block doesn't stop.
In Firefox the mouseover
event is fired without moving the mouse manually over the div, but only if you've moved the mouse at least once.
My question is there a workaround so an element moved under the mouse cursor will still have its mouseover
event fired?
<script>
$(function() {
var move = 10,
left = 0,
width = 100;
var stop = setInterval(function() {
left += move;
$('#mydiv').css('left', left);
if (left < 0 || (left + width > parseInt($(window).width())))
move = -1 * move;
}, 10);
$('#mydiv').mouseover(function() { clearInterval(stop); });
});
</script>
<div id="mydiv" style="width: 100px; height: 100px; position: absolute; top: 0; left: 0; background-color: Black;"> </div>
I know the example is contrived, but it is just to demonstrate the issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个浏览器错误。
唯一的解决方法是在
document
级mousemove
处理程序中跟踪全局鼠标坐标,然后在动画期间检查元素是否覆盖了这些坐标。This is a browser bug.
The only workaround would be to track the global mouse coordinates in a
document
-levelmousemove
handler, then check during the animation whether the element covers those coordinates.