我试图让一个 div 在 React 项目中使用纯 JS 做一个简单的幻灯片到父 div 中,但我在幻灯片的平滑度方面遇到了问题。当我控制台日志时,我可以看到当代码 (slideIn) 运行时,在 setInterval 调用之间,React 运行其他代码,这些代码占用的时间超过指定的间隔。因此,间隔不均匀,这似乎是造成幻灯片抖动的原因。
我也尝试过 requestAnimationFrame,但结果是一样的。
挑战似乎是让 slideIn 连续运行,而不是在运行它的同时 react 运行其他代码,但如何做到这一点?
<div className="outer-box">
<div className="sliding-box"></div>
</div>
.outer-box {
width: 300px;
height: 200px;
position: relative;
}
.sliding-box {
width: 100%;
height: 100%;
position: absolute;
top: 0;
}
slideIn() {
const moveElemment = document.getElementById('sliding-box');
const pos = -100;
if (moveElemment) {
const id = setInterval(frame, 10);
function frame() {
if (pos == 0) {
clearInterval(id);
} else {
pos++;
moveElemment.setAttribute('style', `left: ${pos}%`);
}
}
}
}
最佳答案
也许您可以利用 CSS 过渡来实现与 JS 线程分离的更流畅的动画,从而解决您的问题?例如,您可以使用 transition
规则和附加选择器更新您的 CSS,如下所示:
.sliding-box {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: -100px; // Initial position of sliding-box
transition: left 1s linear; //Specify the animation behaviour
}
.sliding-box.in {
left: 0px; // Position of sliding-box after animation
}
用简化的JS触发转场动画如下:
slideIn() {
const moveElemment = document.getElementById('sliding-box');
if (moveElemment) {
// When this selector is added, it triggers the animation
// transition from left:-100px to left:0px over a 1 second
// interval
moveElemment.classList.add('in');
}
}
关于javascript - 由于其他代码在间隔之间运行,setInterval 函数的间隔不均匀;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51625283/