我目前正在构建 Wes Bos Javascript 30 元素。 将元素变成了待办事项应用程序。而且我不知道如何使用 vanilla javascript 在新创建的复选框上使用 shift-clicking。
关于如何做到这一点的任何见解?
const addBtn = document.querySelector('.addBtn');
const myInput = document.getElementById('myInput');
const toDo = document.querySelector('.toDo-container');
const checkbox = document.querySelectorAll('.toDo-container input[type=checkbox]');
addBtn.addEventListener('click', newElement);
myInput.addEventListener("keyup", function(e){
if(e.keyCode === 13){
e.preventDefault()
newElement() }
});
// Create a new item when clicking on the "Add" button
function newElement(){
let div = document.createElement('div');
let input = document.createElement('input');
let inputValue = document.getElementById('myInput').value;
let textNode = document.createTextNode(inputValue);
let p = document.createElement('p');
div.className = "item";
input.type = "checkbox";
p.appendChild(textNode);
div.appendChild(input);
div.appendChild(p);
toDo.appendChild(div);
if(inputValue !== ""){
document.getElementById("myInput").value = "";
}
}
// Shift Clicking Checkboxes.
let lastChecked;
function shiftClick(e){
let inBetween = false;
if(e.shiftKey && this.checked){
checkbox.forEach(box => {
if(box === this || box === lastChecked){
inBetween = !inBetween
}
if(inBetween){
box.checked = true;
}
});
}
lastChecked = this;
}
checkbox.forEach(box => box.addEventListener('click', shiftClick));
https://codepen.io/iameddieyayaya/pen/XGWaQN?editors=1011
非常感谢!
埃迪·G。
最佳答案
您可以在按下 shift 键时设置一个标志,并在释放键时重置它。然后您的点击监听器可以根据标志的状态有条件地采取行动。 (我不知道像我在这里所做的那样聚焦整个容器是否是确保您不会错过任何击键的最佳方法,但它确实有效。)
const container = document.getElementById("container");
const box = document.getElementById("box");
let shiftIsDown = false;
container.addEventListener("keydown", setShiftFlag);
container.addEventListener("keyup", setShiftFlag);
box.addEventListener("click", handleBoxClick);
container.focus();
function setShiftFlag(event){
if(event.code == "ShiftLeft" || event.code == "ShiftRight"){
if(event.type == "keydown"){
shiftIsDown = true;
}
else if(event.type == "keyup"){
shiftIsDown = false;
}
}
}
function handleBoxClick(){
if(shiftIsDown){
console.log("shift-click");
}
else{
console.log("click");
}
}
body{ height: 100px; }
#container{ width: 100%; height: 100%; }
<body>
<div id="container" tabindex="0">
<input type="checkbox" id="box" />
</div>
</body>
关于Javascript Shift-Click 复选框 To Do App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010444/