3

我有这个简单的 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...

所以又是什么问题!什么错误!我有什么想念的?!

4

2 回答 2

3

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

标准 CSS 不支持background-position-xand background-position-y,只有少数像 Chrome 一样支持。

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

所以毕竟,看看这个http://snook.ca/archives/javascript/jquery-bg-image-animations。如果您想为背景位置设置动画,应该有一个调用的 jQuery 插件jQuery.bgpos.js非常有效。

代码是这样的:

(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);
于 2012-01-18T18:29:28.653 回答
2

似乎您正在对 jQuery 使用笨拙的方法。这可以单独使用 css 完成:

span {
    background: url(yourimage.jpg) top left no-repeat;
    transition: all 3s ease-in-out;
}

span:hover {
    background-position: 50% 50%;
}

背景位置变化将在现代浏览器中动画化,在 IE8 及以下版本中将只是静态变化。

您可能还想添加该transition属性的其他浏览器特定的前缀版本:

-webkit-transition:  
-moz-transition:  
-o-transition:  
transition:
于 2012-01-18T19:06:42.023 回答