2

我有以下无法编辑的标记,因为它是由我无权访问的服务器生成的。服务器使用“contentBox”类加载所有 div,但是它只显示第一个(其他三个display: none;添加了“”)。

我想添加一个ID为'switchButton'的div,这样当它被点击时它会淡出第一个'contentBox' div,然后淡入第二个'contentBox' div等(所以再次按下它,隐藏第二个,显示第三个 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>
4

1 回答 1

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

于 2013-03-25T11:12:28.213 回答