对于一个网站,我做了一个JS,在滚动时对div进行动画处理。我正在对 CSS top 值进行动画处理,但由于我已将该属性应用了过渡,因此我必须想出一种对"top"进行动画处理的方法,而不会产生 CSS 过渡导致的滞后。
我在一个函数中想出了这个:
//Get the Div Element
var div = document.querySelector('.someclass');
//Disable Transition
div.style.transition= 'none';
//Change the top value - value was connected to scroll
div.style.top = anumber + 'px';
//Reset Transition to the CSS's file default
div.style.transition = '';
但这再次导致了不必要的滞后,因为它以某种方式忽略了"禁用转换"步骤。
为了确保每个步骤都能执行,我想出了将"重置"步骤包装到 setTimeout 函数中的想法。我更改了这一行:
//Reset Transition to the CSS's file default
div.style.transition = '';
to
//Reset Transition to the CSS's file default
setTimeout(function () {
div.style.transition = '';
},1);
而塔达,它奏效了。但是现在我想知道,是否有一种更干净的方法来防止第一行不被执行,当然还有解释为什么它甚至会发生。
我感谢所有的帮助!
对 DOM 的更改仅在 CSS 引擎运行时反映到底层模型,这仅在 JS 停止运行时发生。通过使用setTimeout
JS结束的执行,CSS引擎有时间运行,然后计时器触发,JS再次运行。
你可以用以下方法更优雅地解决ut:
const tick = () => new Promise(resolve => setTimeout(resolve));
(async function() {
//Get the Div Element
var div = document.querySelector('.someclass');
//Disable Transition
div.style.transition= 'none';
//Change the top value - value was connected to scroll
div.style.top = anumber + 'px';
await tick();
//Reset Transition to the CSS's file default
div.style.transition = '';
})();