DevEd 教程中的滚动功能不起作用

Scroll function from DevEd tutorial is not working

我看过这个教程https://www.youtube.com/watch?v=oUSvlrDTLi4,我做的和这里一样,我只是用 ES6 标准替换了 var to let。

function scroll(target, duration = 1000) {
  target = document.querySelector(target) + window.scrollY;
  let targetPos = terget.getBoundingClientRect().top;
  let startPos = window.pageYOffset;
  let distance = targetPos - startPos;
  let startTime = null;

  function animation(currentTime) {
    if (startTime === null) startTime = currentTime;
    let timeElapsed = currentTime - startTime;
    let run = ease(timeElapsed, startPos, distance, duration);
    window.scrollTo(0, run);
    if (timeElapsed < duration) requestAnimationFrame(animation);
  }

  function 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);
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.a {
  width: 100%;
  height: 100vh;
  background: green;
}

.b {
  width: 100%;
  height: 100vh;
  background: yellow;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div class="a">
    <h1 onclick="scroll('.b', 1000)">Scroll</h1>
  </div>
  <div class="b">
    <h1 onclick="scroll('.a', 1000)">Scroll</h1>
  </div>
</body>

</html>

不过好像不行。

  1. 将函数名称更改为不与 window.scroll 冲突。
  2. target 应该是元素本身或 document.querySelector(target).
  3. target 在函数的第二行拼写错误。

function myScroll(target, duration = 1000) {
  target = document.querySelector(target);
  let targetPos = target.getBoundingClientRect().top;
  let startPos = window.pageYOffset;
  let distance = targetPos - startPos;
  let startTime = null;

  function animation(currentTime) {
    if (startTime === null) startTime = currentTime;
    let timeElapsed = currentTime - startTime;
    let run = ease(timeElapsed, startPos, distance, duration);
    window.scrollTo(0, run);
    if (timeElapsed < duration) requestAnimationFrame(animation);
  }

  function 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);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    .a {
      width: 100%;
      height: 100vh;
      background: green;
    }
    
    .b {
      width: 100%;
      height: 100vh;
      background: yellow;
    }
  </style>
</head>

<body>
  <div class="a">
    <h1 onclick="myScroll('.b', 1000)">Scroll</h1>
  </div>
  <div class="b">
    <h1 onclick="myScroll('.a', 1000)">Scroll</h1>
  </div>
</body>

</html>