简体   繁体   English

如何滚动到元素并在到达视口顶部时停止?

[英]How to scroll to element and stop when reaches the top of viewport?

I'm working on a website ( http://dev-caeoli.pantheonsite.io/ ) and I'm stuck with a jquery problem. 我正在一个网站( http://dev-caeoli.pantheonsite.io/ )上工作,但遇到了jquery问题。 I'm using scrollTop in the navigation of the website. 我在网站的导航中使用scrollTop。 I can't use anchor links because the "main" element has position fixed in the beginning to create that scroll effect. 我无法使用锚链接,因为“ main”元素的开头位置已固定,无法创建滚动效果。

I'm using this code, but when the scroll occurs, the element stays below the viewport. 我正在使用此代码,但是发生滚动时,该元素将保持在视口下方。

scrollTop: $("#work").offset().top

What I want is the element to scroll to the top of the viewport. 我想要的是滚动到视口顶部的元素。 I've used the code blow to achieve that, but it only works when you are on the top of the page because it subtracts the height of the window. 我使用了代码打击来实现这一点,但是它仅在您位于页面顶部时才起作用,因为它会减去窗口的高度。

scrollTop: $("#hero").offset().top-100 + window.innerHeight

Any clues of what I'm doing wrong? 我做错了什么线索吗?

您应该将当前滚动量添加到元素的offset()。to并分散固定的标题高度

scrollTop: $(window).scrollTop() + $("#work").offset().top - 100

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

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