1、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 to do it without any libraries</p>
</div>
<div class="item">
<input type="checkbox">
<p>Just regular JavaScript</p>
</div>
<div class="item">
<input type="checkbox">
<p>Good Luck!</p>
</div>
<div class="item">
<input type="checkbox">
<p>Don't forget to tweet your result!</p>
</div>
</div>
2、CSS部分
<style>
html {
font-family: sans-serif;
background: #ffc600;
}
.inbox {
max-width: 400px;
margin: 50px auto;
background: white;
border-radius: 5px;
box-shadow: 10px 10px 0 rgba(0,0,0,0.1);
}
.item {
display: flex;
align-items: center;
border-bottom: 1px solid #F1F1F1;
}
.item:last-child {
border-bottom: 0;
}
/*:check伪类选择器代表任何选中或者切换到on状态的单选(如<input type="radio">、checkbox或者option元素)*/
input:checked + p {
background: #F9F9F9;
text-decoration: line-through;
}
{
margin: 20px;
}
p {
margin: 0;
padding: 20px;
transition: background 0.2s;
flex: 1;
font-family:'helvetica neue';
font-size: 20px;
font-weight: 200;
border-left: 1px solid #D1E2FF;
}
</style>
3、JavaScript部分
3.1 先获取所有input的值
const checkboxs = document.querySelectorAll('.inbox input[type = checkbox]');
这里有需要注意的
因为querySelectorAll得到的不是规范的阵列,所以我们需要在外面加一个Array.from()来规范它
const checkboxs =Array.from(document.querySelectorAll('.inbox input[type = checkbox]'));
3.2 由于是多个input,所以要做遍历循环,并对点击事件进行监听
checkboxs.forEach((item)=>{
item.addEventListener("click",clickHandler)
})
function clickHandler(e){
console.log(e);
}
因为需要用shiftkey(shift按钮)来实现,所以我们在控制台找到shiftKey是一个布尔值。如果按住shift键同时点击选项,那么shiftKey为true,否则为false。
3.3 由于要做多选,所以要这样
3.3.1 第一步:设置一个变量来定义第一个选中的东西(firstCheck)
let firstCheck = null;
3.3.2 第二步:判断元素是否被选中
if(this.checked){
firstCheck = checkboxs.indexof(this);
}else{
firstCheck = null;
}
3.3.3 第三步:两个条件
①首先要确定shift键是打开的
②其次你有一个选中的值,lastCheck就是用来判断的。
let firstCheck;
if(this.checked){
lastCheck = checkboxs.indexof(this);
checkboxes.slice(
Math.min(nowCheck,firstCheck),
Math.max(nowCheck,firstCheck)
).forEach(input=>(inpput.checked = true))
firstCheck = checkboxes.indexof(this);
}else{
lastCheck = null;
}
:::知识点
这里要注意,因为firstCheck是一个数值的判断,而电脑是会将数字转化为true或者false来执行,所以如果选择列表第一个(数值为0),那么电脑就会把0转化为false,所以当选择列表第一个数字的时候,按住shift键要多选是执行不了的。在以后如果变量的类型是数值的,那么不能直接扔进if语句进行判断,一定要把它的判断条件写完整。
slice中由于不知道选中的顺序是什么(可能从前面选,也可能从后面选,所以要用Math来进行对比)
slice是一个选择区间的函数
:::