如何使用jquery动画无限循环?

时间:2016-11-11 02:25:45

标签: javascript jquery html css marquee

我一直在尝试使用jquery animate来运行正在运行的文本。但我似乎无法让它在无限循环中运行。它总是只运行一次..



/*  js:  */

$(document).ready(function(){
  function scroll() {
    $('.scroll').animate({ 
      right: $(document).width() 
    }, 8000, scroll); 
  }
  scroll();
});

/* css: */

.scroll {
  position: absolute;
  right: -200px;
  width: 200px;
}

<!-- html: -->

<div class="scroll">This text be scrollin'!</div>
&#13;
&#13;
&#13;

这是演示: https://jsfiddle.net/y9hvr9fa/1/

你们知道如何解决它吗?

2 个答案:

答案 0 :(得分:3)

所以这就是我所做的:

  1. 预先计算$(document).width(),就像出现水平滚动一样,宽度会在下一次迭代中改变

  2. 删除您为width设置的scroll,以便宽度只与内容一样长 - 您必须提供white-space:nowrap才能保留文字一行。

  3. animate中使用scroll

  4. 使用$('.scroll').outerWidth()文字的宽度

    请参阅下面的演示和update fiddle here

    &#13;
    &#13;
    $(document).ready(function() {
      
      // initialize
      var $width = $(document).width();
      var $scrollWidth = $('.scroll').outerWidth();
      $('.scroll').css({'right': -$scrollWidth + 'px'});
      
      // animate
      function scroll() {
        $('.scroll').animate({
          right: $width
        }, 8000, 'linear', function() {
          $('.scroll').css({'right': -$scrollWidth + 'px'});
          scroll();
        });
      }
      scroll();
    });
    &#13;
    body {
      overflow: hidden;
    }
    .scroll {
      position: absolute;
      white-space: nowrap;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="scroll">This text be scrollin'!</div>
    &#13;
    &#13;
    &#13;

    让我知道您对此的反馈,谢谢!

答案 1 :(得分:1)

CSS替代方案:

或者,您可以使用此CodePen中的CSS转换: https://codepen.io/jamesbarnett/pen/kfmKa

更高级:

&#13;
&#13;
$(document).ready(function(){
    var scroller = $('#scroller'); // scroller $(Element)
    var scrollerWidth = scroller.width(); // get its width
    var scrollerXPos = window.innerWidth; // init position from window width
    var speed = 1.5;
    scroller.css('left', scrollerXPos); // set initial position
    
    function moveLeft() {
    	if(scrollerXPos <= 0 - scrollerWidth) scrollerXPos = window.innerWidth;
    	scrollerXPos -= speed;
      scroller.css('left', scrollerXPos);
      window.requestAnimationFrame(moveLeft);
    }
		window.requestAnimationFrame(moveLeft);
});
&#13;
.scroll {
  display: block;
  position: absolute;
  overflow: visible;
  white-space: nowrap;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroller" class="scroll">This text be scrollin'!</div>
&#13;
&#13;
&#13;

肮脏的解决方案(我的原始答案):

在这个例子中,这将是一个快速修复:

文本向左运行而没有停止。在这里,您将告诉文本始终从该位置开始。 (时间过后 - 意味着不一定只是它离开了屏幕)

$(document).ready(function(){
    function scroll() {
      $('.scroll').css('right', '-200px').animate({ 
         right: $(document).width() 
      }, 8000, scroll); 
    }
    scroll();
});