JQuery Animate setTimeout

时间:2018-05-25 06:45:47

标签: javascript jquery jquery-animate settimeout

作为主题,如何为jQuery设置超时?谢谢

$(document).ready(function(){
    animateM();
});
function newPosition(){
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];
}
function animateM(){
    var newq =  newPosition();
    $('.animateM').animate({ top: newq[0], left: newq[1] }, function(){
        animateM();
    });
};

2 个答案:

答案 0 :(得分:1)

在基本方案中,将参数传递给setTimeout执行的回调的首选跨浏览器方法是使用匿名函数作为第一个参数。:

function newPosition(){
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];
}

$(document).ready(function(){

    var newq =  newPosition();

    setTimeout(function() {
        $('.animateM').animate({
            top: newq[0],
            left: newq[1],
        });
    , 2000 ); // 2000 is duration

});

答案 1 :(得分:0)

试试这个

$(document).ready(function(){
 var newq =  newPosition();
$(".animateM").animate({left:newq[1]}, "2000")
           .animate({top:newq[0]}, "5000");
        
});
function newPosition(){
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];
}
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div  class="animateM"  style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>