简体   繁体   English

为什么我的 Javascript 代码中的元素在达到 200px 后不会停止移动?

[英]why does the element in my Javascript code not stop moving after it reaches 200px?

the "voila" element in my code won't stop after reaching 200px?我的代码中的“voila”元素在达到 200px 后不会停止?
what is the problem in the logic of the code?代码逻辑有什么问题?
and how do I make it work.以及如何使它工作。

 var voila = document.querySelector(".voila"); voila.textContent = "hahahaha"; voila.style.position = "absolute"; setInterval(function() { var left = parseInt(window.getComputedStyle(voila).getPropertyValue("left")); if (left >= 0) { voila.style.left = left + 2 + "px"; } else if (left <= 200) { voila.style.left = left - 10 + "px"; } }, 10);
 * { padding: 0; margin: 0; }
 <div class="voila"></div>

any help?有什么帮助吗?

I think you wanted to do this.我想你想这样做。

 var voila = document.querySelector(".voila"); voila.textContent = "hahahaha"; voila.style.position = "absolute"; setInterval(function() { var left = parseInt(window.getComputedStyle(voila).getPropertyValue("left")); if (left >= 0 && left <= 200) { voila.style.left = left + 2 + "px"; } }, 10);
 * { padding: 0; margin: 0; }
 <div class="voila"></div>

And the css way of doing it (works better)css的做法(效果更好)

 .voila { x-transition: all 1s ease-in-out; animation: anim 1.7s infinite; position: absolute; } @keyframes anim { 0% { left: 0; } 50% { left: 200px; } 100% { left: 0; } }
 <div class="voila">ABC</div>

this part else if (left <= 200) is non sens这部分else if (left <= 200) is non sens

you can do that:你可以这样做:

 const voila = document.querySelector('.voila'); voila.textContent = 'hahahaha'; voila.style.position = 'absolute'; voila.mov = { pos: 0, min: 0, max:200, stepOn: 2, stepBack: -10, step: 2 } setInterval(() => { voila.mov.pos += voila.mov.step if (voila.mov.pos >= voila.mov.max) voila.mov.step = voila.mov.stepBack if (voila.mov.pos <= voila.mov.min) voila.mov.step = voila.mov.stepOn voila.style.left = `${voila.mov.pos}px` }, 10)
 * { padding: 0; margin: 0; }
 <div class="voila"></div>

You can also use requestAnimationFrame()您也可以使用requestAnimationFrame()

 const voila = document.querySelector('.voila') voila.textContent = 'hahahaha'; voila.style.position = 'absolute'; voila.mov = { pos: 0, min: 0, max:200, stepOn: 2, stepBack: -10, step: 2 } function movInOut() { voila.mov.pos += voila.mov.step if (voila.mov.pos >= voila.mov.max) voila.mov.step = voila.mov.stepBack if (voila.mov.pos <= voila.mov.min) voila.mov.step = voila.mov.stepOn voila.style.left = `${voila.mov.pos}px` requestAnimationFrame(movInOut) } requestAnimationFrame(movInOut)
 *{ padding: 0; margin: 0; }
 <div class="voila"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM