【问题标题】:Animate div on hover and mouseleave with delay动画 div 悬停和鼠标离开延迟
【发布时间】:2014-09-16 15:50:48
【问题描述】:

我有蓝色 div,它应该在将鼠标悬停在绿色 div 上时进行动画处理。

因此,如果您将光标在绿色 div 上保持足够长的时间,蓝色 div 就会展开。当您将光标移开时,蓝色 div 会恢复到原来的大小。

但是,如果您只是将鼠标快速移动到绿色 div 上,则不会发生任何事情。这种行为的这一部分正是我的问题。如何解决?

http://jsfiddle.net/H435A/

$('#c').hover(function(){
    $('#nav').delay(150).animate({'top':'-=10px', 'left':'-=10px', 'width':'+=20px', 'height':'+=20px', 'background-color':'orange'}, {duration : 200});
    }, function() {
    $('#nav').stop(true).delay(150).animate({'top':'+=0px', 'left':'+=0px', 'width':'-=0px', 'height':'-=0px', 'background-color':'blue'}, {duration : 200});
});

$('#c').mouseleave(function(){
    $('#nav').animate({'top':'+=10px', 'left':'+=10px', 'width':'-=20px', 'height':'-=20px', 'background-color':'blue'}, {duration : 100});
});

【问题讨论】:

    标签: javascript jquery function jquery-animate jquery-hover


    【解决方案1】:

    您的方法在浏览器上可能很繁重。我认为在这种情况下使用 CSS3 过渡会更好。尝试将这些规则应用于您的样式表:

    #c {
        position: relative;
        width: 80px;
        height: 80px;
        background-color: blue;
        -webkit-transition: all .2s ease-in-out;
        -moz-transition: all .2s ease-in-out;
        transition: all .2s ease-in-out;
    }
    #c:hover, #c:focus {
        top: -10px;
        left: -10px;
        width: 100px;
        height: 100px;
        background-color: orange;
        -webkit-transition-delay: .2s;
        -moz-transition-delay: .2s;
        transition-delay: .2s;
    }
    

    当然,您需要稍微更改它们。我分配了一些随机的静态宽度和高度值,因为我无法从您的代码示例中获取它们,但它可以按照您尝试实现的方式工作。

    这里是工作示例:DEMO

    更新

    我做了另一个例子,在你的代码中使用了 CSS 方法。抱歉我之前错过了。 Take a look!

    【讨论】:

    • +1 我认为这应该被接受为一个答案,人们不应该依赖沉重的 js 动画,应该使用 css 过渡来做 web 上的动画。 Javascript 应该只用于添加或删除可能的动画类。
    • 1.广泛的兼容性对我来说非常重要,2. java 可以做的远不止 css - 这只是功能的一小部分,3. 这个小提琴根本不是我需要的。
    【解决方案2】:

    在这里,在mouseleave 事件中,您只需要检查动画是否已完成:DEMO

    var hovered=false;
    $('#c').hover(function(){
        $('#nav').delay(150).animate({'top':'-=10px', 'left':'-=10px', 'width':'+=20px', 'height':'+=20px', 'background-color':'orange'}, 200,function(){
            hovered=true;
        });
        }, function() {
        $('#nav').stop(true).delay(150).animate({'top':'+=0px', 'left':'+=0px', 'width':'-=0px', 'height':'-=0px', 'background-color':'blue'},200);
    });
    
    $('#c').mouseleave(function(){
        if(hovered==true){
            hovered=false;
            $('#nav').animate({'top':'+=10px', 'left':'+=10px', 'width':'-=20px', 'height':'-=20px', 'background-color':'blue'},100);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 2016-12-20
      • 1970-01-01
      • 2014-01-10
      • 2011-08-20
      • 2010-12-03
      • 2012-03-12
      相关资源
      最近更新 更多