javascript 如何用按钮控制水平滚动?

envsm3lx  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(106)

这个想法是,当我点击按钮时,滚动应该在我点击的方向移动,而按钮是按下的。它在第一次尝试时工作,但突然停止工作。

export default function initCarousel() {
  const carousel = document.querySelector("[data-carousel='scroll']");
  const rightBtn = document.querySelector("[data-carousel='right']");
  const leftBtn = document.querySelector("[data-carousel='left']");

  let timer;
  leftBtn.addEventListener("mousedown", () => {
    timer = setInterval(() => {
      carousel.scrollLeft -= 50;
    }, 20);
  });

  rightBtn.addEventListener("mousedown", () => {
    timer = setInterval(() => {
      carousel.scrollLeft += 50;
    }, 20);
  });

  leftBtn.addEventListener("mouseup", () => {
    if (timer) clearInterval(timer);
  });

  rightBtn.addEventListener("mouseup", () => {
    if (timer) clearInterval(timer);
  });
}

字符串

ogq8wdun

ogq8wdun1#

您的代码看起来正确处理鼠标按下事件时按钮的水平滚动。然而,它可能由于各种原因而停止工作。下面是一些需要研究和思考的项目:

document.addEventListener("DOMContentLoaded", function() {
  initCarousel();
});

function initCarousel() {
  const carousel = document.querySelector("[data-carousel='scroll']");
  const rightBtn = document.querySelector("[data-carousel='right']");
  const leftBtn = document.querySelector("[data-carousel='left']");

  let timer;

  leftBtn.addEventListener("mousedown", () => {
    timer = setInterval(() => {
      carousel.scrollLeft -= 50;
    }, 20);
  });

  rightBtn.addEventListener("mousedown", () => {
    timer = setInterval(() => {
      carousel.scrollLeft += 50;
    }, 20);
  });

  document.addEventListener("mouseup", () => {
    if (timer) clearInterval(timer);
  });
}

字符串

相关问题