Created
February 25, 2023 04:43
-
-
Save tiam-bloom/ef5f5fb96975bdccb56e322a8cc5643d to your computer and use it in GitHub Desktop.
列表选择Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Document</title> | |
<style> | |
li { | |
list-style: none; | |
border: 1px solid black; | |
margin: 5px; | |
padding: 5px; | |
} | |
.selected { | |
background-color: #ccc; | |
} | |
</style> | |
</head> | |
<body> | |
<ul id="ul"> | |
<li>单击某个单选</li> | |
<li>Ctrl+Click 多选</li> | |
<li>Shift+Click 选择范围内的项</li> | |
<li>类似文件管理中的选择</li> | |
<li>toggle 有则删除, 无则添加</li> | |
<li>contains 是否包含</li> | |
<li>add 添加</li> | |
<li>remove 删除</li> | |
<li>当选中两个且不在相邻位置时</li> | |
<li>处理方式?</li> | |
</ul> | |
<script> | |
// 阻止浏览器默认选择文字 | |
ul.onmousedown = (e) => e.preventDefault(); | |
ul.onclick = (e) => { | |
if (e.target.tagName != "LI") return; | |
const len = ul.children.length; | |
// 点击按下Ctrl键时 | |
if (e.ctrlKey) { | |
e.target.classList.toggle("selected"); | |
// 点击按下Shift键时 | |
} else if (e.shiftKey) { | |
let start = 0,end = 0; | |
// 处理方式一: 寻找第一个选中的元素, | |
while(start<len && !ul.children[start].classList.contains("selected")) start++; | |
// 寻找当前点击的元素 | |
while(end<len && ul.children[end] != e.target) end++; | |
// 交换start和end的值 | |
if (start > end) [start, end] = [end, start]; | |
// 选中范围内的元素 | |
while (start <= end) ul.children[start++].classList.add("selected"); | |
} else { | |
// 清除所有选中的元素 | |
for (item of ul.children) | |
item.classList.remove("selected"); | |
// 选中当前点击的元素 | |
e.target.classList.add("selected"); | |
} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment