2014-11-05 17 views
2

我正在使用內聯塊元素製作字幕。 目前,我的問題是以有效的方式實現無限滾動。 滾動的結尾是這樣的:內聯塊元素的純javascript水平字幕

end

和起始位置是:

start

但我需要實現無限的效果。我不知道如何去做這件事,通過交換內部元素或其他東西。

你能幫我解釋一下這個小小的項目嗎?

作爲參考,這是結束位置768,16如何看起來像:

end-desired

的代碼很簡單(See CodePen here):

HTML

<div class="viewport" id="viewport"> 
    <div class="wrapper" id="wrapper"> 
    <div class="item">1</div><div 
    class="item">2</div><div 
    class="item">3</div><div 
    class="item">4</div><div 
    class="item">5</div><div 
    class="item">6</div><div 
    class="item">7</div><div 
    class="item">8</div><div 
    class="item">9</div><div 
    class="item">10</div> 
    </div> 
</div> 

CSS

.viewport { 
    position:  relative; 
    margin:  0 auto; 
    padding:  20px 0; 
    width:   200px 
} 
.wrapper { 
    position:  relative; 
    display:  inline-block; 
    white-space: nowrap; 
    transition: 0.8s ease-in-out all; 
} 
.item { 
    display:  inline-block; 
    width:   25px; 
    height:  25px; 
} 

JS

var scroller = document.getElementById('wrapper'); 

function start() { 
    for (var i = 0; 
     i < scroller.children.length; 
     i++) { 

    (function(j) { 
     var timeout = 1000*j; 
     setTimeout(function() { 

     var left = -scroller.children[j].offsetWidth * j, 
      leftPx = left + 'px'; 

     scroller.style.left = leftPx; 

     }, timeout) 
    })(i); 
    } 
} 
start(); 

回答

0

我會假設你想知道如何保持持續的功能,而不是如何動畫回來。在開始結束時調用函數MyFunction();,並在該調用結束時調用start。例如:

var scroller = document.getElementById('wrapper'); 

function start() { 
    for (var i = 0; 
     i < scroller.children.length; 
     i++) { 

    (function(j) { 
     var timeout = 1000*j; 
     setTimeout(function() { 

     var left = -scroller.children[j].offsetWidth * j, 
      leftPx = left + 'px'; 

     scroller.style.left = leftPx; 

     }, timeout) 
    })(i); 
    } 
    MyFunction(); 
} 

// Reverse function here 
start(); 

或者,您可以使用<marquee>標籤,而不是這一切的腳本。

+0

這不是我正在尋找的東西。有關jQuery的示例,請參閱http://als.musings.it/ – 2014-11-05 23:39:31

+0

因此,您希望它更像幻燈片? – CaffeineToCode 2014-11-05 23:40:29

+0

對,就是這個想法。我正在尋找一種好的和有效的方式來做到這一點。我也在擺弄一種我會作爲答案發布的方式,但我希望看到其他人的看法如何解決這個問題 – 2014-11-05 23:41:12