jquery - 自定义 "animate"jQuery 函数。如何重置步骤的 "now"变量?

标签 jquery background jquery-animate background-position

我需要使用 jQuery 对元素的背景位置属性进行动画处理。通过遵循本教程(使用默认的 jQuery 动画函数),我没有运气。

http://snook.ca/archives/javascript/jquery-bg-image-animations

我的功能是这样的:

$('#content').css( {backgroundPosition: "0 0"} )
             .animate(
                 {backgroundPosition:"(0 -900px)"}, 
                 {duration:500}
             );

我没有运气,所以我尝试编写自己的函数来更改元素的垂直背景位置。它看起来像:

$.fn.moveBackgroundY = function( pixels, duration, easing ) {

    return this.animate(
                { pixels: pixels },
                {
                    step: function(now,fx) {

                        console.log("Background Y position - " + now);

                        $(this).css({
                            backgroundPosition: '0px ' + now + 'px',
                        });
                    },
                    duration: duration,
                    complete: function() {
                        $(this).css({
                            backgroundPosition: '0px 0px',
                        });
                    }
                }, easing);
};

要将元素的 Y 背景位置动画设置为 -900,我这样调用该函数:

$('#content').moveBackgroundY(-900, 2100, 'easeInOutCubic');

请注意,这里 step: 内的变量 now(背景位置 Y)将从 0 减小到 -900。

这很好用,但我的问题来了。之后,我需要直接使用 jQuery .css() 函数将此背景位置重置为“0px 0px”,然后再次对其进行动画处理,如下所示:

$('#content').moveBackgroundY(300, 2100, 'easeInOutCubic');

在这种情况下,当我将背景位置重置为“0px 0px”时,参数now应该从0到300,但它从-900到300,其中-900是我首先调用我的函数设置的值。

任何人都知道出了什么问题,或者我如何重置此参数,以便每次都采用正确的值?

我有另一个类似的函数,可以旋转元素并更改 CSS3 属性变换 - 旋转,我也有同样的问题。

感谢您的帮助!

最佳答案

这对我有用:

return this.animate(
            { pixels: pixels },
            {
                step: function(now,fx) {
                    var calculatedPixels = this.pixels;
                    console.log("Background Y position - " + now);


                    $(this).css({
                        backgroundPosition: '0px ' + calculatedPixels + 'px',
                    });
                },
                duration: duration,
                complete: function() {
                    $(this).css({
                        backgroundPosition: '0px 0px',
                    });
                    //not so sure about this but you have to do this somehow
                    this.pixels = 0;
                }
            }, easing);

位置重置问题来自于您正在设置“像素”值而不是背景位置的动画。 然后您将“像素”值应用到backgroundPosition。 然后重置backgroundPosition,但不重置“像素”值。 下一个动画将以最新的像素值作为起始值。 您必须找到一种方法以某种方式将“pixels”值重置为backgroundPosition值,以保持它们同步。

关于jquery - 自定义 "animate"jQuery 函数。如何重置步骤的 "now"变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8911581/

相关文章:

java - jQuery 多文件上传插件

jquery - 无法操纵轮播指示器的右边距/位置

html - 如何在最大宽度内容 div 后面拉伸(stretch)背景图像

jquery - 单击关闭其他打开的 div

javascript - 如何在悬停中使用velocity.js?

html - Opencart 背景图像/颜色错误

css - 我想让DIV里面的背景固定,只有内容随滚动移动,怎么办?

javascript - 使用 animate() JQUERY 获取进度

javascript - jquery animate() 函数没有在表单上触发

jquery - 图像 slider 中的元素符号导航