javascript - 在 jquery 单击上循环跨度

标签 javascript jquery css html

<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 添加/删除类吗?

最佳答案

使用 jQuery .hide() ,您可以先将它们全部隐藏。然后在单击时增加一个变量,并将其值与 % 4 进行比较其中 4 是可用跨度的总数。取消隐藏 :eq()为变量的当前值。

$(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

注意如果 child 的数量<span>变化,你会想使用 $('#facts span').length作为模 %比较而不是硬编码的 4,如下所示:

$('#facts span:eq(' + (current % $('#facts span').length) + ')').show();

关于javascript - 在 jquery 单击上循环跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221677/

相关文章:

javascript - 复杂的异步流程未能按预期执行

javascript - 强制顺序执行 javascript 的替代方法

javascript - 如何在 React 中测试类组件

jquery 数据表自定义过滤器在用户与表交互之前不会重绘表

javascript - 切换多个跨度

jquery - 在 CSS 中移除 DIV 边框

javascript - AngularJS 动态表单字段添加必需属性

php - 引导表在大量记录上加载时间较长

javascript - 设置一个 "unattainable"下拉列表背景覆盖其他元素

CSS 定位 : container doesn't fit to its content size