简体   繁体   中英

How to smooth scroll to div on scroll using vanilla JS?

I'm looking for a way to scroll to a div on scroll - only on the landing Id not looking for full page scroll across all sections.

The JS in my snippet has worked on click event but can't get it working on scroll

 document.getElementById('landing').addEventListener("scroll", function(event) { event.preventDefault(); document.getElementById("main").scrollIntoView({ behavior: "smooth" }); });
 #landing, #main { height:100vh; } #main { background: #EAEAEA; }
 <section id="landing"></section> <section id="main"></section>

I think your problem is that #landing is not overflowing so it isn't scrolling.

I've tried to add more content to the div and it's working

Look at this: scroll() event not firing when attached to a div

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM