Java Shift-Click复选框“待执行”

时间:2019-03-05 19:48:00

标签: javascript css dom

我目前正在建立Wes Bos Javascript 30项目。 将项目变成一个待办应用。而且我不知道如何使用香草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

一吨!

Eddie G。

1 个答案:

答案 0 :(得分:1)

您可以在按下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>