Soy nuevo en javascript, por favor tengan paciencia conmigo. Cuando se presiona la tecla de flecha derecha, me gustaría cambiar el div 100 píxeles a la derecha. Uso mi propia clase para crear un cuadrado y luego trato de cambiar la posición de esta instancia.
class Square { constructor(length) { this.width = length; this.height = length; this.div = document.createElement("div"); this.div.style.position = "absolute"; // to be able to move it this.div.style.backgroundColor = "red"; this.div.style.width = length + "px"; this.div.style.height = length + "px"; document.body.appendChild(this.div); this.xPos = 50; this.div.style.left = this.xPos + "px"; } } var square2 = new Square(10); window.addEventListener( "keydown", function (event) { if (event.defaultPrevented) { return; // Do nothing if the event was already processed } switch (event.key) { case "ArrowDown": alert("ArrowDown"); // Do something for "down arrow" key press. break; case "ArrowUp": // Do something for "up arrow" key press. break; case "ArrowLeft": alert("ArrowLeft"); // Do something for "left arrow" key press. break; case "ArrowRight": alert("ArrowRight"); square2.div.style.left += 100 + "px"; // this code does nothing? break; default: return; // Quit when this doesn't handle the key event. } // Cancel the default action to avoid it being handled twice event.preventDefault(); }, true );
El código square2.div.style.left += 100 + "px";
no hace nada.
No hace nada, simplemente no hace lo que pretendes.
square2.div.style.left
se establece en 50px
, que luego se concatena con 100 + 'px'
lo que da como resultado 50px100px
.
La solución manual es analizar el número cada vez quitando el px
, convirtiendo la cadena en un número ( para evitar la concatenación ) y luego agregándolo.
square2.div.style.left = +square2.div.style.left.replace('px', '') + 100 + "px";
Pero esto es engorroso en el mejor de los casos. La solución más simple es declarar una propiedad left
e incrementarla en su oyente.
class Square { constructor(length) { ... this.xPos = 50; this.div.style.left = this.xPos + "px"; this.left = this.xPos; //<-- declare new left prop set to initial value } } window.addEventListener( "keydown", function (event) { ... case "ArrowRight": square2.left += 100; // increment left prop square2.div.style.left = square2.left + "px";
class Square { constructor(length) { this.width = length; this.height = length; this.div = document.createElement("div"); this.div.style.position = "absolute"; // to be able to move it this.div.style.backgroundColor = "red"; this.div.style.width = length + "px"; this.div.style.height = length + "px"; document.body.appendChild(this.div); this.xPos = 50; this.div.style.left = this.xPos + "px"; this.left = this.xPos; } } var square2 = new Square(10); window.addEventListener( "keydown", function (event) { if (event.defaultPrevented) { return; // Do nothing if the event was already processed } switch (event.key) { case "ArrowDown": alert("ArrowDown"); // Do something for "down arrow" key press. break; case "ArrowUp": // Do something for "up arrow" key press. break; case "ArrowLeft": // Do something for "left arrow" key press. break; case "ArrowRight": square2.left += 100; square2.div.style.left = square2.left + "px"; // this code does nothing? break; default: return; // Quit when this doesn't handle the key event. } // Cancel the default action to avoid it being handled twice event.preventDefault(); }, true );
En mi opinión, la mejor manera de manejar los cambios de estado visual en html usando vanilla js es usar CSS de vainilla. Es menos código. es más limpio Es más fácil admitir a otros desarrolladores en el futuro.
input_element.addEventListener('keyup', (event) => { if (event.key === 'ArrowRight') { event.target.dataset.shift = 'right' } if (event.key === 'ArrowLeft') { event.target.dataset.shift = 'default' } })
.shift[data-shift='right'] { margin-left: 100px; }
<input id="input_element" class="shift" data-shift="default" />
class Square { constructor(length) { this.width = length; this.height = length; this.div = document.createElement("div"); this.div.style.position = "absolute"; // to be able to move it this.div.style.backgroundColor = "red"; this.div.style.width = length + "px"; this.div.style.height = length + "px"; document.body.appendChild(this.div); this.xPos = 50; this.div.style.left = this.xPos + "px"; } } var square2 = new Square(10); window.addEventListener( "keydown", function (event) { // if (event.defaultPrevented) { // return; // Do nothing if the event was already processed // } console.log(event.key) switch (event.key) { case "ArrowDown": alert("ArrowDown"); // Do something for "down arrow" key press. break; case "ArrowUp": // Do something for "up arrow" key press. break; case "ArrowLeft": alert("ArrowLeft"); // Do something for "left arrow" key press. break; case "ArrowRight": alert("ArrowRight"); square2.div.style.marginLeft += 100 + "px"; // this code does nothing? break; default: return; // Quit when this doesn't handle the key event. } // Cancel the default action to avoid it being handled twice event.preventDefault(); }, true );