<!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>
#box{
height:200px;
width:200px;
background-color: red
;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
let box=document.getElementById("box")
// 上=38
document.onkeydown=function(event){
let speed=10
if(event.ctrlKey){speed=100}
if(event.keyCode==38){
box.style.top=box.offsetTop-speed+"px"
}
if(event.keyCode==40){
box.style.top=box.offsetTop+speed+"px"
}
if(event.keyCode==39){
box.style.left=box.offsetLeft+speed+"px"
}
}
// 下=40
// 左=37
// 右=39
</script>
</body>
</html>
这篇博客介绍了如何使用JavaScript监听键盘事件,通过上、下、左、右四个方向键来控制网页中指定div元素的移动。通过设置不同的速度值,实现元素位置的实时更新,为前端学习者提供了一个实用的交互示例。
833

被折叠的 条评论
为什么被折叠?



