使用JavaScript自定义按键移动图片
先上效果图
思路:使用DOM事件和event.keyCode获取自定义的按键码然后进行图片的移动
JS代码如下
var obj = document.getElementById("img");
obj.left = 0;
obj.top = 0;
var getTop,getBom,getLeft,getRight;
var inpTop,inpBom,inLeft,inpRight;
function direc(a) {
var key = event.keyCode;
alert(event.keyCode);
if (a == "up"){
inpTop= key;
}
if (a == "bom"){
inpBom= key;
}
if (a == "left"){
inLeft= key;
}
if (a == "right"){
inpRight= key;
}
}
function f() {
getTop= inpTop;
getBom= inpBom;
getLeft= inLeft;
getRight= inpRight;
alert(up+":"+bom+":"+left+":"+right);
define();
}
function define(){
console.log(event.keyCode);
var key = window.event.keyCode;
if(key == parseInt(getLeft) || key == 37){
//左
obj.left -=80;
}
if(key == parseInt(getTop) || key == 38){
//上
obj.top -=80;
}
if(key == parseInt(getRight) || key == 39){
//右
obj.left +=80;
}
if(key == parseInt(getBom) || key == 40){
//下
obj.top +=80;
}
obj.style.left = obj.left+'px',obj.style.top = obj.top+'px';
}
document.onkeydown = define;