如何实现一键取消SHIFT批量选中后指定复选框后的选中项
实现Shift批量选中后一键取消后续复选框的功能
我已经通过JavaScript实现了利用SHIFT键选中复选框的功能,现需实现一键取消选中的特定功能:在使用SHIFT键批量选中复选框后,点击其中一个已选中的复选框,一键取消该复选框之后所有已选中的复选框。
原HTML代码
<div class="inbox"> <div class="item"> <input type="checkbox" /> <p>This is an inbox layout.</p> </div> <div class="item"> <input type="checkbox" /> <p>Check one item</p> </div> <div class="item"> <input type="checkbox" /> <p>Hold down your Shift key</p> </div> <div class="item"> <input type="checkbox" /> <p>Check a lower item</p> </div> <div class="item"> <input type="checkbox" /> <p>Everything in between should also be set to checked</p> </div> <div class="item"> <input type="checkbox" /> <p>Try do it without any libraries</p> </div> </div>
修改后的JavaScript代码
const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]'); const checkboxArray = Array.from(checkboxes); // 转成数组方便获取索引 let lastChecked; function handleCheck(e) { let inBetween = false; // 保留原有Shift批量选中逻辑 if (e.shiftKey && this.checked) { checkboxes.forEach(checkbox => { if (checkbox === this || checkbox === lastChecked) { inBetween = !inBetween; } if (inBetween) { checkbox.checked = true; } }); } // 新增:取消当前复选框之后所有选中项的逻辑 else if (!this.checked && !e.shiftKey) { const currentIndex = checkboxArray.indexOf(this); // 遍历当前索引之后的所有复选框,取消选中状态 checkboxArray.slice(currentIndex + 1).forEach(checkbox => { checkbox.checked = false; }); } lastChecked = this; } checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck) );
功能说明
- 保留原有Shift批量选中功能:按住Shift键点击复选框时,仍会选中当前点击项与上一次选中项之间的所有复选框。
- 新增取消后续选中项功能:未按住Shift键时,点击已选中的复选框(取消它的选中状态),会自动将该复选框之后的所有复选框都取消选中。
- 索引处理:将
NodeList转为数组,方便通过indexOf获取当前点击复选框的位置,精准遍历后续元素。
内容的提问来源于stack exchange,提问作者xaviour1504
相关产品推荐
相关产品推荐

