我想在JavaScript中实现一个电梯。只是最简单的形式。有几个级别和电梯。当用户点击某个级别时,电梯就在那里。如果用户在电梯仍然要到达其第一个目的地时点击几个级别,电梯必须记住级别的位置,并按顺序停在每个级别。所以最后我写了一些看起来像工作代码的东西。但我认为逻辑错误,导致电梯有时会中断当前的行动并进入最终指定的目的地。 这里是代码JavaScript事件队列
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Lift</title>
<style>
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.building {
width: 400px;
height: 600px;
border: 1px solid #CCC;
margin: auto auto;
}
.floors {
width: 70%;
height: 600px;
border: 1px solid #AAA;
float: left;
}
.floors .level {
width: 100%;
height: 100px;
border-bottom: 1px solid #AAA;
position: relative;
}
.lift-shaft {
width: 30%;
height: 600px;
border: 1px solid #AAA;
float: right;
position: relative;
}
.lift {
width: 100%;
height: 100px;
border: 1px solid blue;
position: absolute;
top: 0;
left: 0;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
</style>
</head>
<body>
<div class="building">
<div class="floors">
<div class="level"></div>
<div class="level"></div>
<div class="level"></div>
<div class="level"></div>
<div class="level"></div>
<div class="level"></div>
</div>
<div class="lift-shaft">
<div class="lift"></div>
</div>
</div>
<script>
(function() {
var levels = document.getElementsByClassName('level'),
theLift = document.querySelector('.lift'),
position = {},
animationInProgress = false;
Array.prototype.forEach.call(levels, function (elem) {
elem.addEventListener('click', function (e) {
position.top = e.target.getBoundingClientRect().top - 10;
animateLift(position.top);
}, false);
});
function animateLift(top) {
if (animationInProgress) {
theLift.addEventListener('webkitTransitionEnd', function (e) {
e.target.style.top = top + 'px';
animationInProgress = false;
}, true);
}
else {
theLift.style.top = top + 'px';
animationInProgress = true;
theLift.addEventListener('webkitTransitionEnd', function (e) {
e.target.style.top = top + 'px';
animationInProgress = false;
}, true);
}
}
})();
</script>
</body>
</html>
这是一个家庭作业? –
不,我不是学生。 – paperstreet7
你已经在标题中回答了你的问题:你需要一个队列(在JS中是一个简单的数组)。目前,您的脚本只有一个写入的“位置”对象。 – Bergi