2013-03-25 137 views
2

我有以下標記,由於無法訪問的服務器生成而無法編輯。服務器加載所有帶有'contentBox'類的div,但它只顯示第一個(其他三個'display: none;'添加到它們)。淡出當前元素並淡化同級元素中的同級元素

我想添加一個ID爲'switchButton'的div,這樣當它被點擊時,它會淡出第一個'contentBox'div,然後淡入第二個'contentBox'div等等(所以再次按下它,隱藏第二,顯示第三格)。

我需要它循環,所以如果它被按下4次,它會返回到第一個框。

<div id="switchButton">Click Me</div> 

    <div class="contentBox">Server side generated content</div> 
    <div class="contentBox">Server side generated content</div> 
    <div class="contentBox">Server side generated content</div> 
    <div class="contentBox">Server side generated content</div> 
+1

[你嘗試過什麼?](http://www.whathaveyoutried.com) – 2013-03-25 11:08:19

+1

我與它開始在所有的,因爲我在索引和循環無望的掙扎。我不知道如何瞄準下一個兄弟姐妹,因爲任何以'contentBox'爲目標的東西都在改變他們。 – JayDee 2013-03-25 11:11:15

回答

5

LIVE DEMO

var c = 0;       // counter 
var n = $('.contentBox').length; // number of elements 

// now using " ++c % n " you can loop your elements 
// targeting the EQuivalent one using .eq() method. (0 indexed) 
// % is called "reminder" or Modulo (AKA Modulus) 


$('#switchButton').click(function(){ 
    $('.contentBox').stop().eq(++c%n).fadeTo(500,1).siblings('.contentBox').fadeTo(500,0); 
}); 

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Arithmetic_Operators
http://api.jquery.com/siblings/
http://api.jquery.com/eq/
http://api.jquery.com/fadeto/

Modulo playground

+0

非常感謝你,它完美的作品。 ++ c%n做什麼?我可以弄清楚c&n指的是變量,但這就是它! – JayDee 2013-03-25 11:17:23

+1

@JayDee在這裏玩:http://jsbin.com/otesub/1/edit – 2013-03-25 11:24:27