[英]How to make scroll work on nav click with scrollTop
我正在尋找使菜單單擊頁面滾動的方法。
我找到的地方。 當我使用translateY時,它可以工作(但是,我不能使用它)。 我需要一個嘗試使用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); } } }
window.scroll將為您工作。 這是單擊滾動按鈕后滾動300px的示例。
在使用它之前,您應該檢查兼容性表中的smooth選項。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.