JavaScript/jQuery中的“if鼠标悬停”或“do while鼠标悬停”

14

有没有一种 JavaScript 或 jQuery 的解决方案,可以在鼠标停留在 DOM 对象上时重复运行函数(使用 setTimeout 之后)?换句话说,是否有 JavaScript 的"do while mouseover"(或 "if mouseover")?

    $('someObject').bind('mouseover', function() {

        //Do the following while mouseover 
        $('someOtherObject').css('margin-left',adjustedLeft + 'px');
        setTimeout(/*do it again*/,25);

    });
5个回答

41
$('someObject').on('mouseenter', function() {
    this.iid = setInterval(function() {
       // do something           
    }, 25);
}).on('mouseleave', function(){
    this.iid && clearInterval(this.iid);
});

查看示例


我使用jQuery的新绑定样式。 - Tadeu Luis
是否可以让事件只在鼠标悬停期间执行一次?目前它会一直执行直到元素停止悬停。我希望只执行一次。 - Shafizadeh
有了 this.iid && clearInterval(this.iid)clearInterval 不足以吗?这样做有何意义? - Adjit

0

我使用jQuery的新绑定样式。

$(el).bind({
'mouseenter': function(){console.log('鼠标悬停');}, 
'mouseleave': function(){console.log('鼠标离开');}
});

0
我会使用onmouseout事件来解决这个问题。 在mouseover事件期间,开始执行您打算执行的任何操作。 当发生onmouseout事件时,我会停止它。

0

我知道这有点老了,但我认为适当的函数已经在JavaScript中了,onmousemove就是这样。


0
OBJ.addEventListener("mouseenter", function() {
  focus=true;
});
OBJ.addEventListener("mouseleave", function() {
  focus=false;
});

如果您不想使用jQuery,可以使用这个 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接