【问题标题】:How to animate 'background-position' with jQuery如何使用 jQuery 为“背景位置”设置动画
【发布时间】:2015-09-27 20:44:21
【问题描述】:

我试图用 jQuery 为 background-position 设置动画,但它似乎不起作用。这是我的小提琴https://jsfiddle.net/nvv5b2dk/border-width 属性动画完美但background-position 没有。任何帮助将不胜感激。

谢谢,

【问题讨论】:

标签: javascript jquery css animation


【解决方案1】:

你可以试试这个:

$('. background').animate({
  'background-position-x': '10%',
  'background-position-y': '20%'
}, 10000, 'linear');

根据这个参考: http://api.jquery.com/animate/

【讨论】:

    【解决方案2】:

    Opera 和 Firefox 不接受 background-position-x/y 动画。您可以尝试使用自定义插件来实现它。

    $('.btn').click(function() {
      $('.background').animate({
        borderWidth: '1px'
      }).animateBG('0', '100px',300);
    });
    
    $.fn.animateBG = function(x, y, speed) {
        var pos = this.css('background-position').split(' ');
        this.x = parseInt(pos[0]) || 0;
        this.y = parseInt(pos[1]) || 0;
        $.Animation( this, {
            x: x,
            y: y
          }, { 
            duration: speed
          }).progress(function(e) {
              this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px');
        });
        return this;
    }
    .background {
      width: 300px;
      height: 200px;
      background: url(http://placehold.it/350x250);
      background-size: cover;
      border: 5px solid;
      border-color: red;
      box-sizing: border-box;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div class='background'></div>
    <input type="button" class='btn' value="Button">

    【讨论】:

    • @NafeesAnwar 你用的是哪个浏览器?
    • 我使用的是 firefox 40.0.3
    • @NafeesAnwar 查看更新后的答案。这是一个复杂的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 2011-07-07
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多