在jquery animate中,如何使用自定义对象而不是div?

Blu*_*ica 3 jquery

我的情况开始是这样的:我想要为div的背景图像设置动画,但似乎用jquery我无法检索背景图像的各个位置(背景位置).所以我想为什么不创建一个对象并为它的值设置动画,然后将这些值放在css中,但我还是想不出如何做到这一点.这是我尝试过的.

var obj={t:0};
                $("#wrapper").animate({
                    obj:100 //I tried obj.t & t as well
                },1000,'linear',function(){},function(){
                    $("#wrapper").css({
                            'background-position':obj.t+"% 0%"
                        });
                });
Run Code Online (Sandbox Code Playgroud)

另外我需要问的另一个问题是,如果图片真的很大,我的意思是大约4000x4000px,将它设置为背景图像并更改背景位置或移动div本身会更好吗?

Gab*_*oli 5

您需要使用animate方法的step功能,更重要的是您需要为实际对象设置动画..而不是#wrapper元素

var obj = {
    t: 0
};

$(obj).animate({ // call animate on the object
    t: 100 // specify the t property of the object to be animated
}, {
    duration: 1000,
    easing: 'linear',
    step: function(now) { // called for each animation step (now refers to the value changed)
        $("#wrapper").css({
            'background-position': now + "% 0%"
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

演示 http://jsfiddle.net/gaby/yPq8s/1/

  • @aoi,确实`step`会激活每个动画的属性..你需要手动处理每个属性的动画......(*`this`指的是你的对象,所以你可以访问所有的值,因为它们是*)[**一个简单的例子**](http://jsfiddle.net/gaby/yPq8s/3/) (2认同)