我需要你们帮助我编写程序,我设法在按下一个键及其 Action 时对其进行编程。但是当我按下键盘“1”时,我的机器人在移动到我的下一个位置之后传送到我的第一个位置。但我需要的是,当按下键盘“1”时,机器人移动到第一个位置然后移动到第二个位置。 请帮助我,因为我是 HTML、CSS 和 java 的新手。 底部是我对该函数的编码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
body {
height: 100%;
width: 100%;
background-image: url("TPHRG floorplan1.png");
background-repeat: no-repeat;
background-attachment: fixed;
/* background-position: center; */
background-size: 980px 400px, cover;
}
.robot_start_top {
top: 280px;
transition: top 2s;
}
.robot_start_left {
position: fixed;
left: 600px;
transition: all 2s;
}
.robot_end_left {
left: 570px;
}
.robot_end_top {
top: 180px;
}
.robot1_start_left {
position: fixed;
left: 570px;
transition: left 4s;
}
.robot1_end_left {
left: 520px;
}
.robot2_start_left {
position: fixed;
left: 520px;
transition: left 4s;
}
.robot2_end_left {
left: 470px;
}
.robot3_start_left {
position: fixed;
left: 470px;
transition: left 4s;
}
.robot3_end_left {
left: 420px;
}
.robot3_start_right {
position: fixed;
left: 470px;
transition: left 4s;
}
.robot3_start_down {
position: fixed;
left: 180px;
transition: left 4s;
}
.robot3_end_down {
top: 280px;
}
.robot3_end_right {
left: 570px;
}
</style>
</head>
<body onkeydown="move(event)">
<div class="robot_start_left robot_start_top" id="app">
<img id="robot" style= width:30px; height:40px" src="pic_8.PNG">
</div>
<script>
var move = function(event) {
if (event.keyCode === 97) {
const appDiv = document.getElementById("app");
setTimeout(function() {
appDiv.classList.add("robot_end_top");
}, 0);
setTimeout(function() {
appDiv.classList.add("robot_end_left");
}, 2000);
}
if (event.keyCode === 98) {
const appDiv = document.getElementById("app");
appDiv.classList.add("robot1_end_left");
}
if (event.keyCode === 99) {
const appDiv = document.getElementById("app");
appDiv.classList.add("robot2_end_left");
}
if (event.keyCode === 100) {
const appDiv = document.getElementById("app");
appDiv.classList.add("robot3_end_left");
}
if (event.keyCode === 13) {
const appDiv = document.getElementById("app");
setTimeout(function() {
appDiv.classList.add("robot3_end_down");
}, 2000);
setTimeout(function() {
appDiv.classList.add("robot3_end_right");
}, 0);
}
}
</script>
</body>
</html>
最佳答案
问题是您想要立即将图像移动到顶部和左侧,而您的 left
参数在这里不起作用,因为您没有将它移动到第一个唯一的左侧点击。要以正确的方式进行操作,您必须将 robot_start_left
中的 left
替换为 all
,如下所示:
.robot_start_left {
position: fixed;
left: 600px;
transition: all 1s;
}
这是 CodeSandBox 中的工作选项.
或者您可以将setTimeout
添加到事件监听器中。这会给你异步效果,就像这样:
if (event.keyCode === 97) {
const appDiv = document.getElementById("app");
setTimeout(function() {
appDiv.classList.add("robot_end_top");
}, 0);
setTimeout(function() {
appDiv.classList.add("robot_end_left");
}, 500);
}
有关更多信息,请阅读此 Article .
祝你好运!
关于javascript - 如何在按键上做多个动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328013/