今日任務:按住Shift鍵,點選兩個Checkbox,並將之間的數個Checkboxes打勾
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((checkbox) => {
checkbox.addEventListener('click', handleCheck);
});
function handleCheck(e){
console.log(this)
}
e.shiftKey
: shift鍵有沒有被按下,回傳true或false
function handleCheck(e){
if(e.shiftKey && this.checked){
//按下shift同時點選打勾時執行
}
}
當被點選時,將被點選的checkbox設為lastCheck
這時再點選另一個checkbox時,就可以用(checkbox === this || checkbox === lastCheck)
來判斷是哪個區間要通通打勾
let lastCheck;
function handleCheck(e) {
if (e.shiftKey && this.checked) {
checkboxes.forEach((checkbox) => {
console.log(checkbox);
if (checkbox === this || checkbox === lastCheck) {
console.log('中間都要打勾');
}
});
}
lastCheck = this;
}
在藍色框起來區域內都要打勾
inBetween預設為false,
跑迴圈當遇到checkbox等於this或等於lastCheck時,inBetween設為true,
會將之後的checkbox都打勾,
直到再次遇到checkbox等於this或等於lastCheck時,設為false,後面不再打勾
let inBetween = false;
function handleCheck(e) {
if (e.shiftKey && this.checked) {
checkboxes.forEach((checkbox) => {
console.log(checkbox);
if (checkbox === this || checkbox === lastCheck) {
inBetween = !inBetween;
console.log('中間都要打勾');
}
if (inBetween) {
checkbox.checked = true;
}
});
}
lastCheck = this;
}
今日學習到的:
效果連結:連結
參考連結:
JS30