【问题标题】:Animating two divs to loop right to left indefinitely动画两个 div 从右到左无限循环
【发布时间】:2016-08-22 16:51:08
【问题描述】:

这是我的代码:

HTML

<div class="screen screen1"></div>
<div class="screen screen2"></div>

CSS

.screen{
    width: 100%;
    height: 50%;
    position: absolute;
    background-color:#001;
    background-image: radial-gradient(white 15%, transparent 16%),
    radial-gradient(white 15%, transparent 16%);
    background-size:60px 60px;
    background-position: 0 0, 30px 30px;
}

.screen2{
    left: 100%;
}

JavaScript

$(document).ready(function(){
    screen1 = $('.screen1');
    screen2 = $('.screen2');

    move(screen1, screen2);
});

function move(first, second){
    first.animate({left: '-100%'}, 3000, function(){
        first.css('left', '100%');
        move(second, first);
    });
    second.animate({left: 0}, 3000);
}

我想使用 jQuery 为两个 div 设置动画以制作无限的背景重复动画。我已经走到这一步了,除了我将.screen1 发送到右侧时发生的小停顿之外,它在大多数情况下都很好用。

这是小提琴:

https://jsfiddle.net/mavisme/a1275tuv/

如何修复它以使其顺利运行?

【问题讨论】:

    标签: javascript jquery html css jquery-animate


    【解决方案1】:

    你应该完全放弃它并尝试 jQuery CSS 动画:

    @keyframes animate {
      from {
        background-position: 0 0;
      }
      to {
        background-position: -60px 0;
      }
    }
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-family: sans-serif;
    }
    
    html, body {
      height: 100%;
      min-height: 100%;
      overflow: hidden;
    }
    
    .screen {
      width: 100%;
      height: 100%;
      position: absolute;
      background-color: #001;
      background-image: radial-gradient(white 15%, transparent 16%), radial-gradient(white 15%, transparent 16%);
      background-size: 60px 60px;
      animation: animate 300ms linear infinite;
    }
    &lt;div class="screen"&gt;&lt;/div&gt;

    【讨论】:

    • 这很好用,但我使用 jQuery 的原因是我正在制作一个需要检测与背景中对象的碰撞的游戏。这意味着背景不能是渐变,必须是更多由 CSS 塑造的 div。
    【解决方案2】:

    我假设您对每个周期开始和结束时的“加速”和“减速”不满意。看看“宽松”:

    function move(first, second) {
        first.animate({
            left: '-100%',
        }, 3000, 'linear', function() {
            first.css('left', '100%');
            move(second, first);
        });
        second.animate({
            left: 0
        }, 3000, 'linear');
    }
    

    缓动(默认:swing)

    一个字符串,指示用于过渡的缓动函数。

    http://api.jquery.com/animate/

    【讨论】:

      【解决方案3】:

      动画两个 div 从右到左无限循环

      这是我的代码:

      https://jsfiddle.net/a1275tuv/5/

       $(function(){
              var x = 0;
              setInterval(function(){
                  x-=1;
                  $('.screen').css('background-position', x + 'px 0');
              }, 10);
          })
      

      【讨论】:

        猜你喜欢
        • 2016-03-01
        • 1970-01-01
        • 2021-11-16
        • 1970-01-01
        • 2014-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多