代码中的"voila“元素在达到200 in后不会停止吗?
代码的逻辑有什么问题?
那我该怎么做呢。
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>
有什么帮助吗?
发布于 2021-05-12 02:27:22
我觉得你想这么做。
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>
以及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>
发布于 2021-05-12 02:29:18
这部分else if (left <= 200)是无意义的。
你可以这样做:
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>
您也可以使用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>
https://stackoverflow.com/questions/67496435
复制相似问题