Video showing the problem. 我正在制作关于赛马游戏的 JavaScript 项目,在赛道上有障碍物, Angular 色应该检测并触发跳跃动画。没有明显的原因,动画以错误的方式触发, Angular 色飞出屏幕,过了一会儿它又回来了,在第二个障碍物处也发生了同样的事情。在视频的开头,我只是展示动画应该是什么样子。
逻辑是关于setInterval构建的,并使用element.offsetTop来运行。 开始按钮触发触发移动功能的间隔。在该函数内,检查 Angular 色的位置和当前选择的(通过i计数器)障碍物。当 Angular 色距离障碍物 80 像素时,if 语句通过向元素添加类名来触发动画,之后我不知道发生了什么。它不应该模仿代达罗斯,而是应该平滑地执行动画,触发另一个 if 语句来计算灌木丛并删除给定的类名以使另一次跳跃可行。
动画的CSS代码
.horse.jump {
animation-iteration-count: 500;
transform: rotate(0deg) scale(1,1);
margin-top: 0;
animation-direction: initial, initial;
background-position:48px -192px;
animation-fill-mode: backwards;
animation: jump 1s;
}
JS代码
var horse = document.getElementsByClassName('horse');
var bush = document.getElementsByClassName('bush');
var i = 0; //Counter for the next obstacle
function horseMoving () {
//Function connecting Start Button with
// moving function by interval
setInterval(moveDown, 9);
}
function moveDown (){
// Cheking character position
var positionHorseUp = horse[0].offsetTop;
//Checking for the current closest obstacle
var positionBushUp = bush[i].offsetTop;
horse[0].classList.add('runDown');
horse[0].style.top = positionHorseUp + 1 + 'px';
//When the character gets close to obstacle
if (positionHorseUp==positionBushUp-80) {
//Makes horse to jump
horse[0].classList.add('jump');
}
//When the character gets away from obstacle
if (positionHorseUp==positionBushUp+20) {
//Takes away the jump class
horse[0].classList.remove('jump');
// This statements prevents an array
// from getting out of elements
// and triggers cheking for next obstacle
if (i<5) {
i++; }
}
}
// These 2 functions are only for video purpose
function showJump() {
horse[0].classList.add('jump')}
function showJump2() {
horse[0].classList.remove('jump')}
function loadFunction() {
var startButton = document.getElementById('start')
startButton.addEventListener('click', horseMoving)
// These 2 lines are only for video purpose
startButton.addEventListener('click', showJump2)
horse[0].addEventListener('click', showJump)
}
document.addEventListener('DOMContentLoaded', loadFunction);
最佳答案
由于您已将动画应用于 jump
类,因此在添加该类时,offsetTop
值实际上会发生更改。因此,您不应该依赖 offsetTop
,而应该使用您自己设置的独立变量,让 offsetTop
依赖于 it 。最初将其设置为 offsetTop
,然后递增它而不是递增 offsetTop
,然后将 top
设置为它。这可能很令人困惑,所以让我发布一些代码。
您可以将其添加到脚本的开头。
var positionHorseUp;
然后将其添加到您的加载事件。
positionHorseUp = horse[0].offsetTop;
然后你会删除这一行...
var positionHorseUp = horse[0].offsetTop;
...并将设置 top
位置的那个替换为这个。
horse[0].style.top = ++positionHorseUp + 'px';
这样,就不会依赖于 offsetTop
值,您可以安全地应用该动画,而不会中断马的存储位置。
(另外,使用 requestAnimationFrame
,而不是 setTimeout
。它的效率更高,因为它会在每个绘制帧上调用。同时添加相应的代码以补偿浏览器环境之间的不确定时间间隔。)
关于javascript - 动画使元素移出屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51318364/