<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div{
position: absolute;
width: 100px;
height: 100px;
background-color: darkred;
left: 100px;
}
</style>
</head>
<body>
<div id="div"></div>
</body>
<script>
var div = document.getElementById('div')
console.log(getComputedStyle(div,null)['left']) //凡是js中没有定义的元素都需要转成字符串传递参数
document.onkeydown = function (event) {
event = event || window.event
console.log(event.keyCode)
if(event.keyCode == 39){
div.style.left = 10 + parseInt(getComputedStyle(div,null)['left']) + 'px'
}
else if(event.keyCode == 37){
div.style.left = -10 + parseInt(getComputedStyle(div,null)['left']) + 'px'
}
else if(event.keyCode == 40){
div.style.top = 10 + parseInt(getComputedStyle(div,null)['top']) + 'px'
}
else if(event.keyCode == 38){
div.style.top = -10 + parseInt(getComputedStyle(div,null)['top']) + 'px'
}
}
</script>
</html>