Осуществление движения объекта.
Есть задумка сделать так, чтобы имеющийся объект(допустим квадрат)при нажатии на стрелочки двигался вверх и вниз. Пересмотрел кучу вариантов, НО ТАК У МЕНЯ НИЧЕГО И НЕ ВЫШЛО. Может кто поможет!?
|
Цитата:
|
<div style="position:absolute; width: 10px; height: 10px; left: 0; top:0; background: red"></div> <script> /** * @class Square * @param {HTMLElement} node * @constructor */ var Square = function (node) { this.x = 0; this.y = 0; this.step = 10; this.node = node; this.setHandlers(); }; Square.prototype.setHandlers = function () { var keys = { 37: "left", 38: "up", 39: "right", 40: "down" }; var that = this; document.addEventListener("keydown", function (e) { if (e.keyCode in keys) { that[keys[e.keyCode]](); that.draw(); } }, false); }; Square.prototype.left = function () { this.x -= this.step; }; Square.prototype.right = function () { this.x += this.step; }; Square.prototype.up = function () { this.y -= this.step; }; Square.prototype.down = function () { this.y += this.step; }; Square.prototype.draw = function () { this.node.style.left = this.x + "px"; this.node.style.top = this.y + "px"; }; new Square(document.querySelector("div")); </script> |
Спасибо!)))
|
Если кому-то ещё понадобится
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #block { width: 25px; height: 25px; background-color: red; position: relative; } </style> </head> <body> <div id="block"></div> <script> window.onload = function () { var left = 0; var top = 0; document.onkeydown = function (){ var block = document.getElementById("block"); switch (event.keyCode) { case 39: //вправо left = left + 10; block.style.left = left + 'px'; break; case 37: //влево left = left - 10; block.style.left = left + 'px'; break; case 38: //вверх top = top - 10; block.style.top = top + 'px'; break; case 40: //вниз top = top + 10; block.style.top = top + 'px'; break; } } } </script> </body> </html> |
Часовой пояс GMT +3, время: 04:27. |