【问题标题】:trying to move box with keys and it is not working试图用钥匙移动盒子但它不工作
【发布时间】:2023-03-09 21:17:01
【问题描述】:

我在这里有一个小提琴: http://jsfiddle.net/maniator/SZpkF/1/

绿色框应该随着箭头键移动。有人可以解释为什么它不起作用吗?

js:

var game = {
    playArea: null,
    player: null,
    init: function() {
        this.playArea = $('<div>', {
            style: 'background-color: #AAF;'
        });
        this.player = $('<span>');
        this.player.css({
            width: 20,
            height: 20,
            'background-color': '#AFA',
            display: 'block',
            position: 'absolute',
            top: 0,
            left: 0
        })
        $(window).resize(game.resize);
        $('body').append(this.playArea);
        this.resize();
        this.playArea.append(this.player);
        $(document).keydown(function(event) {
            game.keydown(event)
        })
        return this;
    },
    resize: function() {
        //console.log('resize', game);
        game.playArea.css({
            width: $(window).width() - 50,
            height: $(window).height() - 50,
        });
        return this;
    },
    keydown: function(event) {
        var direction;
        switch (event.keyCode) {
        case 38:
            direction = {
                'top': '-= 15'
            };
            break;
        case 40:
            direction = {
                'top': '+= 15'
            };
            break;
        case 37:
            direction = {
                'left': '+= 15'
            };
            break;
        case 39:
            direction = {
                'left': '-= 15'
            };
            break;
        }
        console.log(direction, event, game.player);
        game.player.animate(direction, 'slow');
    }
};

$(function() {
    game.init();
})

【问题讨论】:

    标签: javascript jquery jquery-animate key


    【解决方案1】:

    看起来 jQuery 不喜欢 -=+= 之后的空格。我删除了这些并且它起作用了,尽管方向相反。

    【讨论】:

    • 另外,使用event.which,它被规范化为跨浏览器。
    • lol ddnt 注意方向是向后的,因为它不起作用。现在我修好了^_^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多