做个人物移动简单案例
效果如下
代码如下
var div0, code, dic = "",
time = 0,
num = 0,
bool = false,
x = 0,
y = 0,
dis = 1;
into();
function into() {
div0 = creatElem();
document.addEventListener("keydown", keydownHandler);
document.addEventListener("keyup", keyupHandler);
setInterval(animation, 16);
}
function creatElem() {
div0 = document.createElement("div");
Object.assign(div0.style, {
width: "32px",
height: "32px",
position: "absolute",
left: "0px",
top: "0px",
backgroundImage: "url(./img/Actor01-Braver03.png)",
})
document.body.appendChild(div0);
return div0;
}
function keydownHandler(e) {
bool = true;
code = e.keyCode;
}
function keyupHandler(e) {
bool = false;
div0.style.backgroundPositionX = "0px";
time = 0;
}
function animation() {
if (!bool) return;
moveAction();
changeImg();
}
function changeImg() {
if (code > 40 || code < 37) return;
time--;
if (time > 0) return;
time = 15;
div0.style.backgroundPositionX = num++ % 4 * -32 + "px";
}
function moveAction() {
switch (code) {
case 37:
if (dic !== "left") {
div0.style.backgroundPositionY = "-33px";
dic = "left";
}
x -= dis;
break;
case 39:
if (dic !== "right") {
div0.style.backgroundPositionY = "-66px";
dic = "right";
}
x += dis;
break;
case 38:
if (dic !== "top") {
div0.style.backgroundPositionY = "-99px";
dic = "top";
}
y -= dis;
break;
case 40:
if (dic !== "bottom") {
div0.style.backgroundPositionY = "0px";
dic = "bottom";
}
y += dis;
break;
}
div0.style.left = x + "px";
div0.style.top = y + "px";
}
人物所用图片