jQuery Animate backgroundPosition无法正常工作 [英] jQuery Animate backgroundPosition not working
问题描述
我正在尝试对某些div的背景位置进行动画处理,然后再做同样的回调动画.
I'm attempting to animate background position of some divs followed by a callback animation that does the same.
我在这里想念什么?
HTML:
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:
JavaScript:
$(function() {
function animateGrid() {
$('.divimg').animate(
{backgroundPosition:"bottom center"},
500, function() {
$('.divimg').animate(
{backgroundPosition:"top center"},
500)
}
);
}
animateGrid();
})
http://jsfiddle.net/jc6212/WPF6H/2/
推荐答案
来自 .animate()
文档 :
所有动画属性均应设置为单个数字值,除非另有说明; [...] 速记CSS属性(例如,字体,背景,边框)不受完全支持.
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.
要仅对backgroundPositionY
进行动画处理,在Chrome中,您可以对上述属性进行动画处理.由于Firefox不支持backgroundPositionY
,因此您可以为不支持该功能的浏览器应用 CSS挂钩支持它:
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();
});
已在Chrome,FF和IE9中测试.应该适用于所有浏览器.
Tested in Chrome, FF, IE9. Should work in all browsers.
这篇关于jQuery Animate backgroundPosition无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!