javascript - 如何根据属性移动类
问题描述
我正在构建一个滑块,无法弄清楚如何将课程从第一个三个孩子移动到下一个,依此类推..
我正在尝试将活动类移动到下一个“数据组”
<ul>
<li class="active" data-group="1">Item 1</li>
<li class="active" data-group="1">Item 2</li>
<li class="active" data-group="1">Item 3</li>
<li data-group="2">Item 4</li>
<li data-group="2">Item 5</li>
<li data-group="2">Item 6</li>
<li data-group="3">Item 7</li>
<li data-group="3">Item 8</li>
<li data-group="3">Item 9</li>
</ul>
我有一个事件监听器附加到上一个/下一个按钮。只是不知道从这里去哪里。
解决方案
data-group
一点点逻辑,您可以通过获取属性并使用它进行一些计算来查看数据来移动您的活动值:
document.getElementById('next').addEventListener('click', e => {
// Get the max group number
let max = Math.max(...[...document.querySelectorAll(`[data-group]`)].map(el => parseInt(el.getAttribute('data-group'))));
// Get the current group
let group = parseInt(document.querySelector('.active').getAttribute('data-group'));
// Remove the active attribute
[...document.querySelectorAll(`[data-group="${group}"]`)].forEach(el => el.classList.remove('active'));
// Increment the group then compare if the group value is larger than the max
// If it is set the group to 1
if(++group > max) group = 1;
// Add the active class to the proper group
[...document.querySelectorAll(`[data-group="${group}"]`)].forEach(el => el.classList.add('active'));
})
.active {color:red;}
<ul>
<li class="active" data-group="1">Item 1</li>
<li class="active" data-group="1">Item 2</li>
<li class="active" data-group="1">Item 3</li>
<li data-group="2">Item 4</li>
<li data-group="2">Item 5</li>
<li data-group="2">Item 6</li>
<li data-group="3">Item 7</li>
<li data-group="3">Item 8</li>
<li data-group="3">Item 9</li>
</ul>
<button id="next">Next</button>
推荐阅读
- python - 如何在 Python 中更改 CSS 类 - 烧瓶网站
- java - 轮询应用程序,直到在 SpringBoot 中满足条件
- java - 找不到依赖项(来自 http://download.java.net/maven/2)
- http - 什么是“可选的 HTTP 响应标头”?
- python-sphinx - :ref 的确切 docutils 等效项:
- html - 如何在 Bootstrap CSS 中的行和列内垂直和水平对齐子项?
- php - 将 WooCommerce 订单总量保存为 Shipstation 的自定义字段
- ios - 如何将 iOS 应用程序与 SQL 数据库连接?
- python - Sqlite 数据库不使用新值更新表?
- c# - 将许多方法中使用的一个硬编码字符串重构为两个