剑轩

js键盘移动div与背景滚动效果

电脑版发表于:2019/8/30 11:13

通过键盘按下事件记录按键

如果按下的时候就去移动div位置,就不能使用组合键了,不能让div斜着走了,所以只做一个按键记录就好了

//存储按键
var keycodes = {};
$(document).keydown(function (event) {
    keycodes[event.keyCode] = true;
});
$(document).keyup(function (event) {
    keycodes[event.keyCode] = false;
});

然后使用一个setInterval刷新位置即可

//刷新地图
setInterval(function () {
    var top = parseInt($("#div1").css("top"));
    var left = parseInt($("#div1").css("left"));

    if (keycodes[87]) {
        $("#div1").css("top", top - 15);
    }
    if (keycodes[65]) {
        $("#div1").css("left", left - 15);
    }
    if (keycodes[68]) {
        $("#div1").css("left", left + 15);
    }
    if (keycodes[83] == true) {
        $("#div1").css("top", top + 15);
    }
    if (keycodes[75] == true) {

    }
}, 50);

背景滚动效果:

//地图滚动
var py = 0;
var gamerun = function () {
    py = py + 2;
    $("#gamemap").animate({ "background-position-y": py }, 50,"linear", function () {
      gamerun();//递归
    });
}




关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢