如何更好地防止鼠标悬停离开时的影响?

11 浏览
0 Comments

如何更好地防止鼠标悬停离开时的影响?

我制作了一个简单的插件,它只是给一个div添加了翻转效果。当我们悬停在一个div上时,div会翻转,但是当我们再次悬停时,又会发生另一个翻转!\n我通过在jQuery的hover()函数的第二个参数函数中添加return: false来修复了这个问题。\n我的问题是,有没有更好的方法来阻止悬停?\nJS代码:\n

$.fn.jflip = function(bgimage) {
    var img = bgimage;
    this.hover(function(){
        $(".fake").animate({
            top: '+=200px'
        }, 500);
        $(".fake1").animate({
            top: '-=200px'
        }, 500);
        $(".fake").delay(300).animate({
            top: '-=200px'
        }, 500);
        $(".fake1").delay(300).animate({
            top: '+=200px'
        }, 500);
    }, function(){
        return false;
    });
}

\nHTML + CSS代码:\n

.flipper {
    background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSMMSb5XY_fztmTj2rSwFNn-nw2zxId1ZJLnuFfy39Rk-g2fHZ1) no-repeat;
    background-size: 98% 98%;
    background-position: 4px 4px;
    width: 400px;
    height: 400px;
    background-color: #eee;             
}
.fake {
    position: relative;
    top: -200px; left: 0;
    height: 200px;
    width: 400px;
    background-color: white;
}
.fake1 {
    position: relative;
    top: 200px; left: 0;
    height: 200px;
    width: 400px;
    background-color: white;
}


\nFiddle(有问题的版本)。\nFiddle(有解决方法的版本)。\n有没有更好的方法来解决这个问题?或者这是唯一的方法吗?\n感谢任何帮助。

0
0 Comments

问题的原因是使用了.hover()方法,该方法是.on( 'mouseenter' ).on( 'mouseleave' )的简写形式。解决方法是只绑定.on( 'mouseenter' )事件。

解决方法的代码如下:

$.fn.jflip = function(bgimage) {
    var img = bgimage;
    this.on( 'mouseenter', function(){
        $(".fake").animate({
            top: '+=200px'
        }, 500);
        $(".fake1").animate({
            top: '-=200px'
        }, 500);
        $(".fake").delay(300).animate({
            top: '-=200px'
        }, 500);
        $(".fake1").delay(300).animate({
            top: '+=200px'
        }, 500);
    }
  });
}

如果这个回答解决了您的问题,我会很感激您能接受这个答案。

0