在纯Javascriot中使用类“ .something”移动所有元素

时间:2018-12-14 21:30:03

标签: javascript html css

我设法用箭头键使div id = "box"在浏览器中移动。现在,我想让班级为div id = "box"的每个.something也要移动。

我尝试用querySelectorAll遍历代码,但是代码总是失败。 有人可以帮我吗?告诉我该怎么做,因为现在我完全迷失了方向。下面的代码仅适用于一个div ID

var box = document.getElementById("box");
document.addEventListener("keydown", function(event) {
var key = event.key;
var left = box.offsetLeft;
var top = box.offsetTop;

console.log("left: ", left);
console.log("top: ", top);


    box.style.top = (top - step) + "px";
    box.style.top = (top - step) + "px";
    box.style.top = (top - step) + "px";
    box.style.top = (top - step) + "px";
var step = 10;

switch (key) {
    case "ArrowUp":
        event.preventDefault();
        box.style.top = (top - step) + "px";
        break;
    case "ArrowDown":
        event.preventDefault();
        box.style.top = (top + step) + "px";
        break;
    case "ArrowLeft":
        box.style.left = (left - step) + "px";
        break;
    case "ArrowRight":
        box.style.left = (left + step) + "px";
        break;
}
console.log("You pressed on: ", key);

});

2 个答案:

答案 0 :(得分:1)

在修复它时采取了一项措施。 可以在这里找到Repl:https://repl.it/@PaulThomas1/FrightenedAgileBrain

document.addEventListener("keydown", function(event) {
  var boxes = document.getElementsByClassName("box");
  var key = event.key;  

  for(var i = 0; i < boxes.length; i++) {
    var box = boxes[i];
    var left = box.offsetLeft;
    var top = box.offsetTop;    
    console.log("left: ", left);
    console.log("top: ", top);   

    var step = 10;

    switch (key) {
        case "ArrowUp":
            event.preventDefault();
            box.style.top = (top - step) + "px";
            break;
        case "ArrowDown":
            event.preventDefault();
            box.style.top = (top + step) + "px";
            break;
        case "ArrowLeft":
            box.style.left = (left - step) + "px";
            break;
        case "ArrowRight":
            box.style.left = (left + step) + "px";
            break;
    } 
    console.log("You pressed on: ", key);  
  }
});

答案 1 :(得分:0)

由于querySelector all会为您提供一个数组,因此,您不能只是简单地对其进行更改,而是必须遍历所有对象。

var elements = document.querySelectorAll('.something');
document.addEventListener("keydown", function(event) {
var key = event.key;
var step = 10;
for(let el of elements){
  let left = el.offsetLeft;
  let top = el.offsetTop;
  el.style.top = (top - step) + "px";

switch (key) {
    case "ArrowUp":
        event.preventDefault();
        el.style.top = (top - step) + "px";
        break;
    case "ArrowDown":
        event.preventDefault();
        el.style.top = (top + step) + "px";
        break;
    case "ArrowLeft":
        el.style.left = (left - step) + "px";
        break;
    case "ArrowRight":
        el.style.left = (left + step) + "px";
        break;
}
}

console.log("You pressed on: ", key);
});

此外,我建议尝试使用jQuery,它使这些事情变得更加简单。尤其是对于初学者来说,它更容易理解,但是您应注意不要忘记这种“香草”的方式。