2

我正在创建一个需要老式 CRT 效果的网站。我的电视静态效果很好,但我需要一个粗大的失真条来上下移动。

为此,我制作了一个宽度为 100%、高度为 200 像素的 div,我想从页面顶部开始,向下移动,然后在到达底部时,拉回顶部,然后重新开始。

我让它一直工作到循环部分。它向下移动,重置到顶部,然后我希望动画的功能重复自身。

这是我的代码:

$(document).ready(function()
{
    //vars
var windowHeight = $(window).height();
var lineHeight = $('#bar').height();
var desiredBottom = windowHeight - lineHeight;
var newPosition = desiredBottom;
var moving = $('#bar');

animate_loop = function()
{
//FUNCTION ACTIONS
moving.animate({top:newPosition},
{
    duration: 2000,
    complete: function() 
    //function on completion - reset to top
    {
        $('#bar').animate({top:0},100);

    }


});

}//end of animate_loop = function()

animate_loop();

});// end of document ready

当我将其设置为动画时,我的栏会向下移动,它完美地拉回顶部,但随后……什么都没有。在此之前我尝试了一些方法,但后来我在这里看到了一个动画循环线程,它以完全相同的方式布局。有人能指出为什么当我尝试执行“animate_loop();”时我的动画不会循环吗?接近尾声?

4

3 回答 3

2

为了清楚起见,省略了您的文档就绪处理程序和配置变量,动画代码本身的最简单选项只是一个完成回调加上一个立即调用的函数表达式

(function loop() {
    moving.animate({top: newPosition}, 2000)
          .animate({top: 0}, 100, loop);
})();

这四行代码块将自动启动(即不需要单独的显式调用),不创建新变量(loop仅在自身范围内可见)并且不使用额外的计时器。

于 2013-09-08T22:42:49.537 回答
1

动画完成后,您可以使用.animate()中的内置函数调用。像这样:

$(document).ready(function () {
    //vars
    var windowHeight = $(window).height();
    var lineHeight = $('#bar').height();
    var desiredBottom = windowHeight - lineHeight;
    var newPosition = desiredBottom;
    var moving = $('#bar');
    animate_loop = function () {
        //FUNCTION ACTIONS
        moving.animate({
            top: newPosition
        }, {
            duration: 2000,
            complete: function ()
            //function on completion - reset to top
            {
                $('#bar').animate({
                    top: 0
                }, 100, animate_loop);
        }
        });
} //end of animate_loop = function()
animate_loop();
}); // end of document ready
于 2013-09-08T21:54:07.877 回答
1
animate_loop = function () {
    //FUNCTION ACTIONS
    moving.animate({ top: newPosition },{
        duration: 2000,
        complete: function () { //function on completion - reset to top
            $('#bar').animate({ top: 0 }, 100, function () {
                animate_loop(); // <--
            });
        }
    });
}

你只需要在最后再次调用它。

于 2013-09-08T21:55:26.743 回答