在Javascript中同时运行两个函数

我创建了一个函数,可以在 vanilla Javascript 中为平滑滚动设置动画,以便可以在所有浏览器上体验滚动行为。

我有两个想要同时滚动的 div,但是在提供的代码段中为 div1 和 div2 运行功能 smoothScroll 只会导致第二个 div 滚动。

是否可以以导致 div 同时滚动的方式运行该函数?

非常感谢任何帮助,如果您需要任何说明,请告诉我。

function smoothScroll(id, scroll, duration)
{
  let startTime = null;
  
  animation = (currentTime) => 
  {
    if(startTime === null) startTime = currentTime;
    const timeElapsed = currentTime - startTime;
    var run = ease(timeElapsed, 0, scroll, duration);
    document.getElementById(id).scrollLeft = run;
    if(timeElapsed < duration) requestAnimationFrame(animation);
  }
  
    ease = (t, b, c, d) => 
    {
      t /= d/2;
      if (t < 1) return c/2*t*t + b;
      t--;
      return -c/2 * (t*(t-2) - 1) + b;
    }
    
    requestAnimationFrame(animation);
  
}

smoothScroll('div1', 100, 1000);
smoothScroll('div2', 50, 1000);
div{
  border: solid black 1px;
  display: flex;
  width: 150px;
  overflow: auto;
  margin: 1rem;
}
<div>
  <h1>Hello world!...................................................</h1>
</div>
<div>
  <h1>Hello world!...................................................</h1>
</div>
<div>
  <h1>Hello world!...................................................</h1>
</div>
<div>
  <h1>Hello world!...................................................</h1>
</div>

回答

您的变量泄漏的范围:既animationease被用作全局变量。

  • `let`, `const` and `var` inside a function d

    function smoothScroll(id, scroll, duration)
    {
        let startTime = null;
      
        const ease = (t, b, c, d) => 
        {
          t /= d/2;
          if (t < 1) return c/2*t*t + b;
          t--;
          return -c/2 * (t*(t-2) - 1) + b;
        }
    
        const animation = (currentTime) => 
        {
          if(startTime === null) startTime = currentTime;
          const timeElapsed = currentTime - startTime;
          var run = ease(timeElapsed, 0, scroll, duration);
          document.getElementById(id).scrollLeft = run;
          if(timeElapsed < duration)
          requestAnimationFrame(animation);
        }
        
        requestAnimationFrame(animation);
    }
    
    smoothScroll('div1', 100, 1000);
    smoothScroll('div2', 50, 1000);

    eclare local variables. If a variable is not declared, it is an error in strict mode, or a global variable outside it. I strongly recommend using [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) to catch these kinds of errors.


以上是在Javascript中同时运行两个函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>