0

我想为背景位置设置动画但不工作。这可以动画吗

<head>
    <style>
        .test{ background:#F00}
    </style>
    <script type="text/javascript" src="jquery-1.8.3.js"></script>
    <script type="text/javascript">
        $(function(){
            $('a').click(function(){
                $(this).animate({backgroundPosition:'-50px 10px'}, 200);
            });
        });
    </script>
</head>

<body>
    <a href="javascript:void(0)">click</a>
    <div>check....</div>
</body>
4

3 回答 3

2

如果您检查jQuery 动画页面,您可以阅读:

动画

所有动画属性都应动画为单个数值,除非以下说明;大多数非数字属性无法使用基本的 jQuery 功能进行动画处理(例如,宽度、高度或左侧可以进行动画处理,但背景颜色不能进行动画处理,除非使用 jQuery.Color() 插件)。

话虽如此,背景位置使用 2 个值。一个解决方案是拼接该值。

这里'如何*:

$(this).animate({
  'background-position-x' : '-50px',
  'background-position-y' : '10px'
}, 200);

*我可能颠倒了你的 2 个值,我不记得哪个是x,哪个是y

编辑

由于 Firefox 不支持background-position-xand y,这里有一个修复它的代码:

var pos = {x : '', y : ''};
$('a').click(function(){
    var that = $(this);
    that.animate({
        'background-position-x' : '-50px',
        'background-position-y' : '10px'
    },{
      duration : 200, 
      step : function(a,b){
         if(b.prop == "backgroundPositionX"){
             pos.x = a + b.unit
         }else if(b.prop == "backgroundPositionY"){
             pos.y = a + b.unit
         }
      },
      progress : function(){
         that.css('background-position', pos.x + ' ' + pos.y);
      }
    });
});
于 2013-05-27T13:53:21.743 回答
1

我忘记了我在哪里遇到的,但这里有一个小插件可以很好地解决这个问题:

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

并在使用中:

$(function(){
    $('a').click(function(){
        $(this).animate({backgroundPosition: "(-50px 10px)"}, 200);
    });
});
于 2013-05-27T19:05:22.177 回答
0

工作 jsFiddle 演示

我认为 jQuery 不能为background-position. 一种解决方案是在 CSS 中使用过渡:

a {
    -webkit-transition: background-position 0.6s;
    -moz-transition:    background-position 0.6s;
    -ms-transition:     background-position 0.6s;
    -o-transition:      background-position 0.6s;
    transition:         background-position 0.6s;
}

只需更改background-positionjQuery with.css()方法:

$(function(){
    $('a').click(function(){
        $(this).css('background-position', '250px 250px');
    });
});
于 2013-05-27T13:53:11.190 回答