jquery
2013-07-09 102 views 1 likes 
1

我打算構建一個具有多個框的小滑塊。我有8個(例如),我需要一次顯示4個。它們就像我想要向上滑動的小橫幅。Javascript滑塊不起作用

這是到目前爲止我的代碼:

HTML:

<div id="boxes"> 
    <div class="current">1</div> 
    <div>2</div> 
    <div>3</div> 
    <div>4</div> 
    <div class='box hide'>5</div> 
    <div class='box hide'>6</div> 
    ... 
</div> 

CSS:

#boxes div{ 
    width:400px; 
    height:60px; 
    background-color: red; 
    color:white; 
    margin: 20px 0; 
} 

.hide{display:none;} 

的Javascript:

$(function(){ 
    setInterval(show_boxes, 2000); 
}) 

function show_boxes(){ 

    var curBox = $("#boxes div.current"); 
    var nxtBox = curBox.next(); 

    if(nxtBox.length == 0){ 
     nxtBox = $("#boxes div:first"); 
    } 

    curBox.removeClass('current').addClass('hide'); 
    nxtBox.addClass('current').removeClass('hide'); 

} 
+0

這是一團糟,你可以給我們一個jsFiddle的任何方式,以及解釋它做什麼和不做什麼?沒有真正的想法,你想要完成什麼或出了什麼問題。 –

+0

如果幫助你,請檢查http://jsfiddle.net/haapN/ –

+0

有沒有考慮過'nxtBox'是第二個盒子,而不是第五個盒子,這是你想改變的那個?另外,考慮一下你穿過第8個盒子展示它會發生什麼?這些將是我對解決這個問題的出發點的建議。 –

回答

2

我會做這樣的事情:

function show_boxes() { 
    // cache the boxes wrapper (for performance) 
    var $boxes = $('#boxes'); 
    // fetch the box we want to hide, which is on top of the list 
    var $toHide = $boxes.find('div:first'); 
    // add it to the end of the list 
    $boxes.append($toHide); 
    // hide it 
    $toHide.addClass('hide'); 
    // show the next box, which is now always the first hidden one 
    $boxes.find('.hide:first').removeClass('hide'); 
} 

請注意,我每次將頂部框移動到列表的末尾。通過這種方式,您將獲得一個很好的無限循環,而且您不必執行復雜的檢查來查看下一個要顯示的框,以及下一個要隱藏的框。

演示: http://jsfiddle.net/XzmAT/2/

而且我刪除了current類,因爲它不會在我的代碼需要。

+0

你是一位出色的PeterVR。謝謝! –

+0

一個問題。我需要一直顯示4個盒子,剩下的要滑動。你能給我一個提示嗎? –

+0

4盒正在小提琴中展示。你滑到什麼意思? – Pevara

相關問題