【发布时间】:2023-03-26 23:41:01
【问题描述】:
我正在尝试让我的<div> 移动得更平滑或沿对角线移动。当按下W 和D 等两个键时,它只向一个方向移动。我想让它对角移动。有没有一种可能的方法可以使运动不那么起伏不定。 divShootingGallery 是父 <div> 或游戏板,divShooter 是临时框。我只想使用 JavaScript 而不是 jQuery。
这是我的代码:
function keyClick(){
var divShooter = document.getElementById("divShooter");
var divGameBoard = document.getElementById("divShootingGallery");
switch(event.keyCode)
{
case 65://a to move left
if(divShooter.offsetLeft > 0){
//checks to make sure the left side of the shooter is not off the left side
divShooter.style.left = divShooter.offsetLeft - 10 + "px";
}else{
divShooter.style.left = "0px";
}
break;
case 68://d to move right
if(divShooter.offsetLeft + divShooter.clientWidth < divGameBoard.clientWidth){
//checks to make sure the right side of the shooter is not off the right side
divShooter.style.left = divShooter.offsetLeft + 10 + "px";
}
else{
divShooter.style.left = (divGameBoard.clientWidth - divShooter.clientWidth) + "px";
}
break;
case 87://w key up for right player
divShooter.style.top = divShooter.offsetTop - 10 + "px";
if(divShooter.offsetTop <= 0){
divShooter.style.top = "0";
}
break;
case 83://s key down for right player
divShooter.style.top = divShooter.offsetTop + 10 + "px";
if(divShooter.offsetTop + divShooter.clientHeight >= divGameBoard.clientHeight){
divShooter.style.top = divGameBoard.clientHeight - divShooter.clientHeight + "px";
}
break;
}
}
window.addEventListener('keydown',keyClick,true);
html,body{
height:100%;
width:100%;
}
#divShootingGallery{
position:absolute;
left:0;
right:0;
margin:auto;
width:1000px;
height:600px;
background:bisque;
}
#divShooter{
position:absolute;
left:475px;
bottom:0;
width:50px;
height:50px;
background:blue;
}
<head>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="divShootingGallery">
<div id="divShooter"></div>
</div>
</body>
【问题讨论】:
标签: javascript animation keyevent