首页 > 解决方案 > 如何根据属性移动类

问题描述

我正在构建一个滑块,无法弄清楚如何将课程从第一个三个孩子移动到下一个,依此类推..

我正在尝试将活动类移动到下一个“数据组”

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

我有一个事件监听器附加到上一个/下一个按钮。只是不知道从这里去哪里。

标签: javascript

解决方案


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>


推荐阅读