Navigate back to the homepage

Day10: Hold Shift and Check Checkboxes

JavaScript30
July 1st, 2021 · 1 min read

專案介紹: 按住 Shift 鍵對多個 checkbox 進行勾選。

作品頁面:https://iris1114.github.io/javascript30/10_Hold-Shift-and-Check-Checkboxes/

做法

  • 取得所有 checkbox 元素
  • 用 forEach 跑,點擊元素再進行 handleCheck() 這個函式

code

1const checkboxes = document.querySelectorAll(".inbox input[type='checkbox']");
2
3let lastChecked;
4
5function handleCheck(e) {
6 let inBetween = false; // 是否按著 Shift 鍵
7 if (e.shiftKey && this.checked) {
8 //檢查是否有按著 Shift 鍵以及是否被勾選
9 checkboxes.forEach((checkbox) => {
10 console.log(checkbox);
11 // 紀錄首先勾選的核取方塊到最後勾選的核取方塊
12 if (checkbox === this || checkbox === lastChecked) {
13 inBetween = !inBetween; //此時inBetween = true
14 console.log("Starting to check them in between!");
15 }
16
17 if (inBetween) {
18 checkbox.checked = true; //inBetween = true 後進行勾選
19 }
20 });
21 }
22
23 lastChecked = this;
24}
25
26checkboxes.forEach((checkbox) => {
27 checkbox.addEventListener("click", handleCheck);
28});

More articles from Iris Blog

Day9: Dev Tools Domination

DOM break on & 練習 console 用法

June 29th, 2021 · 1 min read

Day8: Fun with HTML5 Canvas

練習操作 Canvas

June 27th, 2021 · 1 min read
© 2020–2021 Iris Blog
Link to $mailto:qweichew@gmail.comLink to $https://github.com/iris1114Link to $https://www.instagram.com/iris.justdoit/Link to $https://www.linkedin.com/in/iris-chew