当用户单击元素时向下滚动页面的 JavaScript 函数

问题描述 投票:0回答:1

我想创建一个 JS 函数,将事件侦听器添加到链接,这样当用户单击该链接时,它将向下滚动页面到特定元素 但由于某种原因它没有成功所以我需要你的帮助

我尝试了这段代码,但它不起作用

function scrollToElement(elementSelector, instance = 0) {
    const elements = document.querySelectorAll(elementSelector);
    if (elements.length > instance) {
      elements[instance].scrollIntoView({ behavior: 'smooth' });
    }
  }
  

const link1 = document.getElementById("link1");
const link2 = document.getElementById("link2");
const link3 = document.getElementById("link3");

link1.addEventListener('click', () => {
  scrollToElement('.features');
});

link2.addEventListener('click', () => {
  scrollToElement('.header', 1);
});

link3.addEventListener('click', () => {
  scrollToElement('.column');
});

javascript web-frontend
1个回答
0
投票

确保该元素可见。

尝试更改您的功能,如下所示:

function scrollToElement(el, instance=0) {
  const elements = document.querySelectorAll(el);
  
  if (elements.length > 0) {
    if(!elements[instance].checkVisibility()) return;

    elements[instance].scrollIntoView({ behavior: 'smooth' });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.