首页 > 解决方案 > 如何将 Jquery.animate 翻译成 Vanilla JS

问题描述

我只使用了 Jquery 代码的一小部分,我想翻译它

  $("html,body").animate(
      {
        scrollTop: sections[counter].offsetTop,
        behavior: "smooth",
      },
      800
    );

Window.scrollTo()不工作

完整代码

let delay = false;

let counter = 0;
// let scrollHeight = 0;

const sections = document.querySelectorAll(".scrolling-block");

function scrollToSection(e, directionY, directionX) {
  if (delay) return;
  // console.log(e);
  delay = true;

  if (directionY !== 0) {
    // if scroll by y
    setTimeout(function () {
      delay = false;
    }, 1500);
  } else {
    // if scroll by x
    delay = false;
  }

  if (directionY !== 0 || directionY !== -0) {
    e.preventDefault();
  }
  if (directionY > 0) {
    //scroll down
    if (counter + 1 !== sections.length) {
      // scrollHeight += sections[counter].clientHeight;
      counter++;
    } else {
      scrollHeight = scrollHeight;
      counter = counter;
    }
    $("html,body").animate(
      {
        scrollTop: sections[counter].offsetTop,
        behavior: "smooth",
      },
      800
    );

    // console.log(scrollHeight + "\n", counter);
    return counter;
  } else if (directionY < 0) {
    //scroll up
    if (counter - 1 !== -1) {
      // scrollHeight -= sections[counter - 1].clientHeight;
      counter--;
    } else {
      scrollHeight = scrollHeight;
      counter = counter;
    }

    $("html,body").animate(
      {
        scrollTop: sections[counter].offsetTop,
        behavior: "smooth",
      },
      800
    );

    // console.log(scrollHeight);
    return counter;
  }
}

window.addEventListener(
  "wheel",
  function (e) {
    let directionY = e.deltaY;

    let directionX = e.deltaX;

    let maxY = sections[sections.length - 1].offsetTop;

    if (pageYOffset < maxY - 10) {
      // console.log(scrollHeight, " < ", maxY);
      if (directionY !== 0) {
        e.preventDefault();
      }
      scrollToSection(e, directionY, directionX);
    } else {
      if (pageYOffset < maxY && directionY < 0) {
        if (directionY !== 0) {
          e.preventDefault();
        }
        scrollToSection(e, directionY, directionX);
      }
      // console.log(scrollHeight, " > ", maxY);
    }

    // e.stopPropagation();
  },
  { passive: false }
);

标签: javascriptjquery

解决方案


从技术上讲,scroll 和 scrollTo 都应该做同样的事情

window.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

或者

window.scroll({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

请在此处查看文档:
[1]:https ://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo [2]:https ://developer.mozilla.org/en-US /docs/Web/API/窗口/滚动


推荐阅读