2017-08-25 173 views
0

我有一个自动滚动栏脚本,使图像向右滚动。我想在结束后重复它。请帮忙!重复水平自动滚动条

<div class="scrolls"> 
    <div> 
     <img src="img1" height="200"/> 
     <img src="img2" height="200"/> 
     <img src="img3" height="200"/> 
    </div>   
</div> 

<script> 
    $(document).ready(function() { 
     var sL = 4000; 
     $('.scrolls').animate({ 
      scrollLeft : sL 
     },100000, 'linear'); 

     $(".scrolls").on("click",function(){ 
       $(this).stop(true,false); 
     }); 

     $(".scrolls").on("mouseenter",function(){ 
      $(this).stop(true,false); 
     }); 

     $(".scrolls").on("mouseleave",function(){ 
      $(this).animate({ 
      scrollLeft : sL 
      },100000, 'linear'); 
     }); 
    }) 
    </script> 

回答

0

采取与时listItems(HTML标记)的无序列表

<div class="scrolls"> 
    <ul> 
     <li><img src="img1" height="200"/></li> 
     <li><img src="img2" height="200"/></li> 
     <li><img src="img3" height="200"/></li> 
    </ul> 
</div> 

拷贝时listItems这样你就可以fillup整体水平空间的两倍。现在向右滚动div,每当图像离开div到左侧时,将它从开始移动到结尾。

// create as many copys as needed for filling the whole harizontal space twice 
var dummyClones = $('.scrolls > ul > li').clone(true); 
while($('.scrolls > ul').width() < 2*$('.scrolls').width()) 
    $('.scrolls > ul').append(dummyClones.clone(true)); 

动画本身是通过window.requestAnimationFrame解决:

var animationSpeedInMiliseconds = 10000; // 10 seconds for 1000px 
function step(timestamp) { 
    if(!step.startTimestamp) step.startTimestamp = timestamp; 
    if(!step.stopped) { 
     let delta = timestamp - step.startTimestamp; 
     let pixelCountToShift = (delta/animationSpeedInMiliseconds) * 1000; 
     if($('.scrolls').scrollLeft()+pixelCountToShift > $('.scrolls > ul > li:eq(0)').width()) { 
      $('.scrolls > ul').append($('.scrolls > ul > li:eq(0)')); 
      $('.scrolls').scrollLeft($('.scrolls').scrollLeft()+pixelCountToShift-$('.scrolls > ul > li:eq(0)').width()); 
     } else { 
      $('.scrolls').scrollLeft($('.scrolls').scrollLeft()+pixelCountToShift); 
     } 
    } 
    step.startTimestamp = timestamp; 
    window.requestAnimationFrame(step); 
} 

注意:它并不完美。这是我在4分钟内创建的一个例子,它应该被理解为概念验证。不是用于生产用途的脚本。

的jsfiddle:https://jsfiddle.net/Kasalop/tktfr4rz/2/

+0

请尝试使用片段是可能的。 – Keith

+0

@Keith不是一个片段的粉丝(我的浏览器安全策略无论如何都会阻止它们),但我保证将来我会继续使用片段。 –