1
<div id="facts">
<p>notes:</p><span class="hide">note 1</span>
             <span class="hide">note 2</span>
             <span class="hide">note 3</span>
             <span class="hide">note 4</span>
</div>

我正在尝试制作一个简单的“幻灯片”循环循环,一次只显示“事实:”右侧的一个跨度,但我似乎无法弄清楚如何让它正常工作。

.hide {
    display: none;
}

.show {
    display: inline;
}

我在想你可以使用 jquery 添加/删除类吗?

4

3 回答 3

3

Using jQuery .hide(), you can first hide all of them. Then increment a variable on click, and compare its value to % 4 where 4 is the total number of available spans. Unhide the :eq() for the variable's current value.

$(document).ready(function() {
    var current = 0;

    // This is bound to the onclick, but you can attach it to any event.
    $('#facts').click(function() {
      // Hide all of them
      $('#facts span').hide();
      // Unhide the current one:
      $('#facts span:eq(' + (current % 4) + ')').show();
      // Increment the variable;
      current++;
    });
});

Here is a live demo

Note that if the number of child <span> varies, you would want to use $('#facts span').length as the modulo % comparison rather than the hard-coded 4 as in:

$('#facts span:eq(' + (current % $('#facts span').length) + ')').show();
于 2012-11-04T18:52:10.200 回答
2

You can use setInterval function:

var $spans = $('span'), i = 0;
setInterval(function(){
     if (i == $spans.length) i = 0;
     $spans.hide().eq(i).show()
     i++   
}, 2000)

http://jsfiddle.net/Chyuw/

于 2012-11-04T18:53:43.333 回答
0

我要做的是有一个带有基本计数变量的函数,以及一个用于重置变量的 if 语句。您可以使用:eq()选择器来选择像数组这样的元素。

i = 0;
$('element').click(function() {
  $('span').hide();
  $('span:eq(i)').show(); // shows only the one indexed span tag
  i++;
  if (i > [amount of span tags]) { // resets i if it gets too big
    i = 0; 
  }
}

所以基本上你只是在不断地迭代。

于 2012-11-04T18:55:10.850 回答