2

我正在尝试为某些 div 的背景位置设置动画,然后是执行相同操作的回调动画。

我在这里想念什么?

HTML:

<div>
    <div class='divimg'></div>
    <div class='divimg'></div>
    <div class='divimg'></div>
</div>
​

CSS:

.divimg {
    width:250px;
    height:250px;
    margin:20px;
    float:left;
    background-size: 500px 500px;
    background-position: top center;
    background-repeat: no repeat;
    background-image: url(http://lorempixel.com/186/116/nature/1);
}​

JavaScript:

$(function() { 
    function animateGrid() {  
        $('.divimg').animate(
            {backgroundPosition:"bottom center"}, 
            500, function() { 
                $('.divimg').animate(
                    {backgroundPosition:"top center"}, 
                500)
            }
        );   
    }
    animateGrid(); 
})​

http://jsfiddle.net/jc6212/WPF6H/2/

4

1 回答 1

3

From .animate() docs:

All animated properties should be animated to a single numeric value, except as noted below; [...] Shorthand CSS properties (e.g. font, background, border) are not fully supported.

To animate just the backgroundPositionY as you're doing, in Chrome you can simply animate said property. As Firefox does not support backgroundPositionY, you can apply a CSS Hook for browsers that do not support it:

if (!('backgroundPositionY' in document.createElement('div').style)) {
    $.cssHooks.backgroundPositionY = {
        get: function(elem, computed, extra) {
            return $.css(elem, 'backgroundPosition').split(' ')[1];
        },
        set: function(elem, value) {
            elem.style.backgroundPosition = $.css(elem, 'backgroundPosition').split(' ')[0] + ' ' + value;
        }
    };
}


$(function() {

    function animateGrid() {
        $('.divimg').animate({
            backgroundPositionY: 250
        }, 500, function() {
            $('.divimg').animate({
                backgroundPositionY: 0
            }, 500);
        });
    }

    animateGrid();
});

Tested in Chrome, FF, IE9. Should work in all browsers.

jsFiddle

于 2012-11-18T18:18:50.880 回答