问题
I'm attempting to animate background position of some divs followed by a callback animation that does the same.
What am I missing here?
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/
回答1:
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
来源:https://stackoverflow.com/questions/13442897/jquery-animate-backgroundposition-not-working