如何使导航点击与scrollTop的滚动工作

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

我正在寻找方法,使在菜单中,点击页面滚动。

我发现的地方去。当我使用平移Y它的工作(但ofcouse我不能使用它)。我需要一个滚动我试图用scrollTop的和scrollBy但它不为我工作。我做错了什么?

function scroll(id: number) {
            for (let k = 0; k < sectionsForScroll.length; k++) {
                if (sectionsForScroll[k].dataset.navId == id) {
                    const bigginer = sectionsForScroll[0].getBoundingClientRect().top;
                    console.log( bigginer + 'px  how far we from the start ');
                    const distanceToGo= sectionsForScroll[k].getBoundingClientRect().top;
                    console.log(sectionsForScroll[k].offsetTop);
                    const distanceToScroll = bigginer - distanceToGo;
                    console.log(distanceToGo + ' where we have to go ');
                    console.log(distanceToScroll + ' what the distanse we need to scroll ');
                    main.style.transform = 'translateY(' + distanceToScroll + 'px)';
                    // main.scrollTop=distanceToGo;
                    // window.scrollBy(0, distanceToGo);
                }
            }
        }
javascript scroll
1个回答
0
投票

window.scroll会为你工作。这里是点击滚动按钮后滚动300像素的一个例子。

使用它之前,您应该结帐的顺利选项compatibility table

document.getElementById("myButton").addEventListener("click", scrollMe);

function scrollMe() {
  window.scroll({
    top: 300,
    left: 0,
    behavior: 'smooth'
  });
}
.myDiv {
  background-color: green;
  height: 1000px;
}
<div class="myDiv">
  <button id="myButton">Scroll</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.