css部分
<style type="text/css">
.top {
border-radius: 10px;
}
.down {
border-radius: 10px;
}
#left {
border-radius: 10px;
}
#right {
border-radius: 10px;
}
#btn {
border-radius: 5px;
}
</style>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<center>
上:<input type="text" onkeyup="change('up')" class="top"><br><br>
下:<input type="text" onkeyup="change('down')" class="down"><br><br>
左:<input type="text" onkeyup="change('left')" id="left"><br><br>
右:<input type="text" onkeyup="change('right')" id="right"><br><br>
<button onclick="modify()" id="btn"><font size="4">修改</font></button>
</center>
<img id="img" src="1.jpg" style="width: 80px;height: 80px;position: absolute;left: 0px;top: 0px;">
<script type="text/javascript">
var obj = document.getElementById("img");
obj.left = 0;
obj.top = 0;
var up, down, left, right;
var up1, downl, left1, right1;
function modify() {
up = up1;
down = downl;
left = left1;
right = right1;
move();
}
function change(str) {
if (str == "up") {
up1 = event.keyCode;
}
if (str == "down") {
downl = event.keyCode;
}
if (str == "left") {
left1 = event.keyCode;
}
if (str == "right") {
right1 = event.keyCode;
}
}
function move() {
console.log(event.keyCode);
//左
if (event.keyCode == 37 || event.keyCode == left) {
obj.left -= 80;
}
//上
if (event.keyCode == 38 || event.keyCode == up) {
obj.top -= 80;
}
//右
if (event.keyCode == 39 || event.keyCode == right) {
obj.left += 80;
}
//下
if (event.keyCode == 40 || event.keyCode == down) {
obj.top += 80;
}
obj.style.left = obj.left + "px",
obj.style.top = obj.top + "px";
}
document.onkeydown = move;
</script>
</body>
</html>
动态效果如下: