简体   繁体   English

如何使用vanilla JS在滚动时平滑滚动到div?

[英]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.我正在寻找一种在滚动时滚动到 div 的方法 - 仅在登陆 Id 上不寻找所有部分的整页滚动。

The JS in my snippet has worked on click event but can't get it working on scroll我的代码段中的 JS 已经在点击事件上工作,但无法让它在滚动上工作

 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.我认为你的问题是 #landing 没有溢出,所以它没有滚动。

I've tried to add more content to the div and it's working我已经尝试向 div 添加更多内容并且它正在工作

Look at this: scroll() event not firing when attached to a div看看这个: 附加到 div 时不会触发 scroll() 事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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