用JS做一个div以键盘上下左右控制移动
整个代码如下做完后发现按住上键(其他键也一样)他会顿一下再一直向上走这个问题应该怎么解决<!DOCTYPEhtml><htmllang="en"><head><metac...
整个代码如下 做完后发现按住上键(其他键也一样) 他会顿一下再一直向上走 这个问题应该怎么解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div1{
width: 100px;
height: 100px;
position: absolute;
background: #CCC;
top:500px;
left: 200px;
}
</style>
<script>
window.onkeydown = function(ev){
var oEvent = ev||event
var oDiv = document.getElementById('div1')
if (oEvent.keyCode== 39) {
oDiv.style.left = oDiv.offsetLeft + 10 +'px'
}else if(oEvent.keyCode == 37){
oDiv.style.left = oDiv.offsetLeft - 10 +'px'
}else if (oEvent.keyCode == 38){
oDiv.style.top = oDiv.offsetTop -10 +'px'
}else if (oEvent.keyCode == 40) {
oDiv.style.top = oDiv.offsetTop +10 +'px'
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html> 展开
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div1{
width: 100px;
height: 100px;
position: absolute;
background: #CCC;
top:500px;
left: 200px;
}
</style>
<script>
window.onkeydown = function(ev){
var oEvent = ev||event
var oDiv = document.getElementById('div1')
if (oEvent.keyCode== 39) {
oDiv.style.left = oDiv.offsetLeft + 10 +'px'
}else if(oEvent.keyCode == 37){
oDiv.style.left = oDiv.offsetLeft - 10 +'px'
}else if (oEvent.keyCode == 38){
oDiv.style.top = oDiv.offsetTop -10 +'px'
}else if (oEvent.keyCode == 40) {
oDiv.style.top = oDiv.offsetTop +10 +'px'
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html> 展开
1个回答
展开全部
只走一步是因为移动一次后没有对x进行处理,所以点第二次的时候 x的值不变,x-10也不变,所以就不动了 <html> <head> <title>demo</title> <style type="text/css"> .active { border: 1px solid red; } </style> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var x = 0;//水平方向位移 var y = 0;//垂直方向位移 $(document).keydown(function (event) { switch (event.which) { case 37: y = y - 10; $("#person").css("left", y + "px"); break; case 38: x = x - 10; $("#person").css("top", x + "px"); break; case 39: y = y + 10; $("#person").css("left", y + "px"); break; case 40: x = x + 10; $("#person").css("top", x + "px"); break; default: break; } }); </script> </head> <body> <div id="person" class="active" style="position: absolute; width: 50px; height: 50px;" /> </body> </html>
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询