gpt4 book ai didi

jQuery animate() backgroundPosition 无法正常工作

转载 作者:行者123 更新时间:2023-12-01 01:03:19 25 4
gpt4 key购买 nike

我有这个简单的 HTML:

<span class="coverImg" style="background-image:url('images/show2.jpg');"></span></a>

和一些 JavaScript:

$(function() {
$(".coverImg").hover(function() {
$(this).animate({
backgroundPosition : "0 0"
}, "fast");
}, function() {
$(this).animate({
backgroundPosition : "50% 50%"
}, "fast");
});
});

因此,当鼠标悬停时,该功能可以正常工作,尽管动画不是那么完美,并且几乎看不到缓动。但是当鼠标移开时,该功能不起作用,背景图像只是坐在那里,即使在像素上也不会移动......

有什么问题吗?我错过了什么?

或者:

$(function() {
$(".coverImg").mouseover(function() {
$(this)
.animate({
"background-position-x" : "-=20px",
"background-position-y" : "-=20px"
}, "fast");
}).mouseout(function() {
$(this).animate({
"background-position-x" : "0 ",
"background-position-y" : "0"
}, "fast");
})
})

这只适用于 Chrome...

那么问题又出在哪里呢!有什么问题!我有什么想念的吗?!

最佳答案

我不认为 jQuery 可以默认设置背景位置动画 - 我使用 http://archive.plugins.jquery.com/project/backgroundPosition-Effect

标准 CSS 不支持 background-position-xbackground-position-y,只有少数支持,例如 Chrome。

并且 jQuery 的 animate() 方法不支持同时对两个值进行动画处理,有时会出现错误,或者在某些浏览器中不执行任何操作。

毕竟,看看这个 http://snook.ca/archives/javascript/jquery-bg-image-animations 。如果您想要为背景位置添加动画效果,应该有一个名为 jQuery.bgpos.js 的 jQuery 插件,该插件可以很好地工作。

代码是这样的:

(function($) {
$.extend($.fx.step, {
backgroundPosition : function(fx) {
if(fx.state === 0 && typeof fx.end == 'string') {
var start = $.curCSS(fx.elem, 'backgroundPosition');
start = toArray(start);
fx.start = [start[0], start[2]];
var end = toArray(fx.end);
fx.end = [end[0], end[2]];
fx.unit = [end[1], end[3]];
}
var nowPosX = [];
nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
fx.elem.style.backgroundPosition = nowPosX[0] + ' ' + nowPosX[1];
function toArray(strg) {
strg = strg.replace(/left|top/g, '0px');
strg = strg.replace(/right|bottom/g, '100%');
strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2");
var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
return [parseFloat(res[1], 10), res[2], parseFloat(res[3], 10), res[4]];
}

}
});})(jQuery);

关于jQuery animate() backgroundPosition 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8915346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com