【问题标题】:Hover Animation Not Completed悬停动画未完成
【发布时间】:2013-05-02 17:15:50
【问题描述】:

这是一个用于说明目的的小提琴: http://jsfiddle.net/wVRtL/

HTML:

    <section class="full-w blue">
        <div class="container">
            <div class="three"></div>
            <div class="two"></div>
        </div>
    </section>


    <section class="full-w red">
        <div class="container">
            <div class="two"></div>
            <div class="three"></div>
        </div>
    </section>

jQuery

$('.full-w').hover(function() {
   marginTopHero = $(this).find('.two').css("margin-top").replace("px", "");
   newMargin = marginTopHero - 50 + "px";
   oldMargin = marginTopHero + "px";

   $(this).find('.two').stop().animate({ 'margin-top': newMargin }, 'fast');
   }, function() {
   $(this).find('.two').stop().animate({ 'margin-top': oldMargin }, 'fast');
});

预期的行为是,当鼠标悬停在线时,黄色矩形会向上移动,当鼠标离开该线时,会向下移动到其原始位置。但是,如果您将指针从一条红线快速移动到另一条红线,您会看到黄色框逐渐升起,直到到达红线的顶部。

我必须检索此元素的 margin-top 值才能在 mouseleave 上恢复到该位置(margin-top 会从一个 .two 变为另一个)

我知道这很棘手,除非我完全错过了什么。

谢谢!

【问题讨论】:

    标签: jquery hover jquery-animate


    【解决方案1】:

    问题可能是您将旧值保存在共享全局变量中,请改用.data() api 来保存以前的值

    $('.full-w').hover(function() {
    
        var marginTopHero = $(this).find('.two').css("margin-top").replace("px", "");
        var newMargin = marginTopHero - 150 + "px";
        $(this).data('oldMargin', marginTopHero + "px")
    
        $(this).find('.two').stop().animate({ 'margin-top': newMargin }, 'fast');
    }, function() {
        $(this).find('.two').stop().animate({ 'margin-top': $(this).data('oldMargin') }, 'fast');
    });
    

    【讨论】:

    • 我认为问题是每次悬停时我都在检索 margin-top,我应该只存储第一个实例。
    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 2015-06-09
    • 2019-05-06
    • 1970-01-01
    • 2018-05-29
    • 2011-07-22
    • 2022-10-06
    • 2013-07-20
    相关资源
    最近更新 更多