JavaScript/jQuery 中的“if mouseover”或“do while mouseover”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3966273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
An "if mouseover" or a "do while mouseover" in JavaScript/jQuery
提问by Kyle
Is there a JavaScript or jQuery solution to run a function repeatedly (after setTimeout
) while the mouse is over a DOM object? Otherwise said, is there a JavaScript "do while mouseover" (or "if mouseover")?
setTimeout
当鼠标悬停在 DOM 对象上时,是否有 JavaScript 或 jQuery 解决方案来重复(在 之后)运行一个函数?否则说,是否有 JavaScript“在鼠标悬停时执行”(或“如果鼠标悬停”)?
$('someObject').bind('mouseover', function() {
//Do the following while mouseover
$('someOtherObject').css('margin-left',adjustedLeft + 'px');
setTimeout(/*do it again*/,25);
});
回答by jAndy
$('someObject').on('mouseenter', function() {
this.iid = setInterval(function() {
// do something
}, 25);
}).on('mouseleave', function(){
this.iid && clearInterval(this.iid);
});
回答by Thariama
I would solve this issue using the onmouseout event. Start whatever you intended to do while the mouse is over the specified component on the mouseover event. When onmouseout event occurs i would stop it.
我会使用 onmouseout 事件解决这个问题。当鼠标悬停在鼠标悬停事件的指定组件上时,开始您打算执行的任何操作。当 onmouseout 事件发生时,我会停止它。
回答by Tadeu Luis
i use new bind style of jQuery.
我使用新的 jQuery 绑定样式。
$(el).bind({ 'mouseenter': function(){console.log('Mouse over');}, 'mouseleave': function(){console.log('Mouse leave');} });
回答by Noobay
I know this is kind of old, but I think the proper function is already in JavaScript, onmousemovedoes just that.
我知道这有点旧,但我认为 JavaScript 中已经有了正确的函数,onmousemove就是这样做的。
回答by Juan Denis
OBJ.addEventListener("mouseenter", function() {
focus=true;
});
OBJ.addEventListener("mouseleave", function() {
focus=false;
});
Just in case you don't want to use jquery you can use this :)
以防万一你不想使用jquery,你可以使用这个:)