Javascript动画图片,滑动bug

时间:2014-01-27 21:49:19

标签: javascript jquery html

我有一个滑动图像,我有一个问题。如果您对图像进行多次快速鼠标悬停,然后将鼠标移到图片之外,它仍会动画。不知何故,即使您没有将鼠标放在它上面,它也能记录和播放动画。 这是我的代码和link来检查它:

<script type="text/javascript">
$(document).ready(function() {
    $('.col-md-4,.col-xs-4').hover( 
    function () {
        $(this).find('#hoverpic').animate({ "top": "-=330px" }, "normal" );
    },
    function () {
        $(this).find('#hoverpic').animate({ "top": "+=330px" }, "normal" );
    });
});
</script>   

4 个答案:

答案 0 :(得分:2)

添加.stop()

   function () {
        $(this).find('#hoverpic').stop().animate({ "top": "-=330px" }, "normal" );
    },
    function () {
        $(this).find('#hoverpic').stop().animate({ "top": "+=330px" }, "normal" );
    });

如果.stop()效果不佳

您可以尝试使用.stop(true).stop(true, true)

http://api.jquery.com/stop

答案 1 :(得分:1)

你应该检查一下

if( $(elem).is(':animated') ) {...}

代码。

<script type="text/javascript">
$(document).ready(function() {
    $('.col-md-4,.col-xs-4').hover( 
    function () {
        if(!$(this).is(':animated'))
        $(this).find('#hoverpic').animate({ "top": "-=330px" }, "normal" );
    },
    function () {
        if($(this).is(':animated'))
        $(this).find('#hoverpic').animate({ "top": "+=330px" }, "normal" );
    });
});
</script>  

答案 2 :(得分:1)

我通常在动画时添加一个类。 像这样:

$(document).ready(function() {
    $('.col-md-4,.col-xs-4').hover( 
    function () {
        if(!$(this).hasClass('animate')) {
            $(this).addClass('animate');
            $(this).find('#hoverpic').animate({ "top": "-=330px" }, "normal" );
        }
    },
    function () {
        if($(this).hasClass('animate')) {
            $(this).find('#hoverpic').animate({ "top": "+=330px" }, "normal", function() { $(this).removeClass('animate'); } );
        }
    });
});

答案 3 :(得分:0)

如果您想在动画结束前悬停时避免跳跃图像,则需要进行简单的更改(请参阅注释代码):

$('.col-md-4,.col-xs-4').hover(
function () {
    $(this).find('#hoverpic').stop().animate(
    { "top": "0px" } //WAS -=330px
    , "normal" );
},
function () {
    $(this).find('#hoverpic').stop().animate({ 
    "top": "330px" //WAS +=330px
    }, "normal" );
});
相关问题