【问题标题】:jQuery background-position animation to run more smoothlyjQuery background-position 动画运行更流畅
【发布时间】:2015-04-22 06:38:06
【问题描述】:

我在 jQuery 中有一个这样的图案背景动画。

        banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');

        window.setInterval(function() {
            banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
            y--;
        }, 150);

现场示例http://codepen.io/anon/pen/emMxXa

但它相当“紧张”。 我怎样才能让这样的东西运行得更顺畅、更慢。

【问题讨论】:

  • 减少间隔延迟,以便每秒获得更多帧:codepen.io/anon/pen/ByrbWO
  • 我建议使用 50 的值,不过移动速度更快 :)

标签: javascript jquery css


【解决方案1】:

看看这个jsFiddle。

您会看到,将区间值从 150 减少到 30 会更加平滑:

             window.setInterval(function() {
                banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
                y--;
                //x--;

                //if you need to scroll image horizontally -
                // uncomment x and comment y

            }, 30);

你可以降低它甚至更多,但你降低它越多,它也变得越快。

【讨论】:

    【解决方案2】:

    看看https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

    (function($) {
    
            var x = 0;
            var y = 0;
            //cache a reference to the banner
            var banner = $("#banner");
    
            // set initial banner background position
            banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
    
            // scroll up background position every 90 milliseconds
            function step() {
                banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
                y--;
                //x--;
    
                //if you need to scroll image horizontally -
                // uncomment x and comment y
                        window.requestAnimationFrame(step)
            }
    
        window.requestAnimationFrame(step);
    
    })(jQuery);
    

    【讨论】:

      【解决方案3】:

      您想使用并查看 CSS 过渡 和 CSS 动画 以获得真正的平滑度。

      -webkit-animation: move 30s linear 0s infinite alternate;
      -moz-animation: move 30s linear 0s infinite alternate;
      
      @-webkit-keyframes move { 
        from { background-position: 0px 0px } to { background-position: 0px 400px }  
      }
      
      @-moz-keyframes move { 
        from { background-position: 0px 0px } to { background-position: 0px 400px }  
      }
      

      演示:http://codepen.io/anon/pen/EaEMvy

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2017-02-20
      • 2019-04-23
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多