题解 | #移动控制#
移动控制
https://www.nowcoder.com/practice/84af7932f53f4bbeaa1fa079a138bb35
function bind() { document.onkeydown = (event) => { if (!event) return; var code = event.keyCode || ""; if (!{ 37: 1, 38: 1, 39: 1, 40: 1 }[code]) return; event.preventDefault && event.preventDefault(); //TODO: 请实现按键控制 let current = document.querySelector("td[class='current']"); let currentParent = current.parentNode; let Parent=currentParent.parentNode if (code === 39) { if ( currentParent.children[currentParent.children.length - 1] === current ) { current.classList.remove("current"); currentParent.children[0].classList.add("current"); } else { current.classList.remove("current"); current.nextElementSibling.classList.add("current"); } } if (code === 37) { if (currentParent.children[0] === current) { current.classList.remove("current"); currentParent.children[ currentParent.children.length - 1 ].classList.add("current"); } else { current.classList.remove("current"); current.previousElementSibling.classList.add("current"); } } if (code === 38) { let index = Array.from(currentParent.children).indexOf(current); if (Parent.children[0] === currentParent) { current.classList.remove("current"); Parent.children[Parent.children.length-1].children[index].classList.add("current") } else { current.classList.remove("current"); currentParent.previousElementSibling.children[index].classList.add("current"); } } if (code === 40) { let index = Array.from(currentParent.children).indexOf(current); if (Parent.children[Parent.children.length-1] === currentParent) { current.classList.remove("current"); Parent.children[0].children[index].classList.add("current") } else { current.classList.remove("current"); currentParent.nextElementSibling.children[index].classList.add("current"); } } }; }