每次鼠标悬停都会触发一次jquery效果

时间:2013-12-18 18:54:13

标签: javascript jquery html

如何在鼠标悬停首次执行后停止jquery效果?我希望盒子反弹一次,即使鼠标留在盒子里也要停止,并且每次鼠标重新进入盒子时重复此操作。目前,当鼠标在盒子内时,它无限地运行效果。提前谢谢。

我在jsfiddle

上做了一个例子

我试过了: one("mouseover", function() { $( "#div1" ).effect("bounce", "slow"); });

然而,当您离开盒子并重新进入盒子时,这不会再次触发事件。

3 个答案:

答案 0 :(得分:5)

.one()有效:

$( "#div1, #div2" ).one('mouseover', function() {
    $(this).effect("bounce", "slow");
});

演示: http://jsfiddle.net/Rxhzg/1/

更新(基于更新的问题)

如果通过“on mouseover once”表示只是“一次反弹” - 添加times参数:

$( "#div1, #div2" ).mouseenter(function() {
    $(this).effect("bounce", { times: 1 }, "slow");
});

DEMO 2 http://jsfiddle.net/Rxhzg/4/

答案 1 :(得分:1)

$( "#div1, #div2" ).one('mouseover', function() {
    $(this).effect("bounce", { times: 1 }, "slow");
});

$( "#div1, #div2" ).mouseleave(function() {
    $(this).one('mouseover', function() {
    $(this).effect("bounce", { times: 1 }, "slow");
});
});

检查此http://jsfiddle.net/Rxhzg/6/

或者检查一下http://jsfiddle.net/Rxhzg/8/,因为如果鼠标位于框底部,上面的内容会继续反弹。

$( ".parentDiv" ).one('mouseover', function() {
    $(this).find('.navBox').effect("bounce", { times: 1 }, "slow");
});

$( ".parentDiv" ).mouseleave(function() {
    $(this).one('mouseover', function() {
    $(this).find('.navBox').effect("bounce", { times: 1 }, "slow");
});
});

答案 2 :(得分:0)

此示例与其他答案类似,但它将原始绑定抽象为可重用性函数。

var $target = $( "#div1, #div2" );

function bounce() {
  $target.one('mouseover', function () {
    $(this).effect("bounce", { times: 1 }, "slow");
  });
}

$target.on('mouseout', bounce);      

bounce();