Показать сообщение отдельно
  #3 (permalink)  
Старый 27.03.2015, 17:14
Профессор
Отправить личное сообщение для tsigel Посмотреть профиль Найти все сообщения от tsigel
 
Регистрация: 12.12.2012
Сообщений: 1,398

<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>
Ответить с цитированием