Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对于Performance animationFrame或onScroll,什么更好?_Javascript_Reactjs_Requestanimationframe - Fatal编程技术网

Javascript 对于Performance animationFrame或onScroll,什么更好?

Javascript 对于Performance animationFrame或onScroll,什么更好?,javascript,reactjs,requestanimationframe,Javascript,Reactjs,Requestanimationframe,我用react创建了一个选框元素。当元素不可见时,我希望字幕停止 以下是我检查可见性的代码: const isVisible = () => { const rect = marqueeRef.current.getBoundingClientRect(); const elTop = rect.top; const elBottom = rect.bottom; const visible = elTop < wHeight && elBottom

我用react创建了一个选框元素。当元素不可见时,我希望字幕停止

以下是我检查可见性的代码:

const isVisible = () => {
  const rect = marqueeRef.current.getBoundingClientRect();
  const elTop = rect.top;
  const elBottom = rect.bottom;
  const visible = elTop < wHeight && elBottom >= 0;
  return visible;
};
这两种方法都会不断检查元素是否可见,因此我想知道是否有人对此有任何经验,并能说明哪种方法性能更好


谢谢。

这台机器非常适合这个。它比这两个选项中的任何一个都有更好的性能,因为它只在元素可见或不可见时调用回调(取决于给定的阈值),并且有一个相对简单的API来引导。

谢谢,我甚至不知道这是可用的,而且它似乎有很好的浏览器支持。请注意,scroll事件仅在绘制帧中调用,因此它比这里的requestAnimationFrame循环要好。但公认的答案是正确的,因为您的案例IntersectionObserver甚至更好。
const animate = () => {
  if (isVisible()) {
    i = i < width ? i + step : 0;
    marqueeRef.current.style.transform = `translateX(${-i}px)`;
  }
  aF = requestAnimationFrame(animate);
};
const onScroll = () => {
  if(isVisible()){
    animate();
  }else{
    cancelAnimationFrame(aF);
  }
}