如果向下滚动屏幕,有一个div粘在屏幕的顶部 [英] Have a div cling to top of screen if scrolled down past it
问题描述
我有一个div,当我的页面第一次加载,从顶部大约100px(它拥有一些按钮等页面)。
用户滚动过它,我想让div跟随用户,因为它附加到屏幕的顶部。当用户返回页面顶部时,我想要它回到其原始位置。
可视化 - xxxxx是div:
默认(页面加载)用户垂直滚动,
--------- ---------
| | | xxxxxxx | <当
| xxxxxxx |时,div到达屏幕顶部| |页面垂直滚动,它保持
| | | |有
--------- ---------
这是用这样的东西,附加一个处理程序到window.scroll事件
//高速缓存选择器外回调的性能。
var $ window = $(window),
$ stickyEl = $('#the-sticky-div'),
elTop = $ stickyEl.offset
$ window.scroll(function(){
$ stickyEl.toggleClass('sticky',$ window.scrollTop()> elTop);
});
这只是添加了一个 sticky
CSS类看起来像这样
#the-sticky-div.sticky {
position:fixed;
top:0;
}
EDIT-修改缓存jQuery对象的代码,现在更快。
I have a div which, when my page is first loaded, is about 100px from the top (it holds some buttons etc. for the page).
When a user scrolls past it, I would like the div to "follow" the user in that it attaches to the top of the screen. When the user returns to the top of the page, I want it back in its original position.
Visualization - xxxxx is the div:
Default (page load) User vertically scrolled well past it
--------- ---------
| | |xxxxxxx| < after div reaches top of screen when
|xxxxxxx| | | page is scrolled vertically, it stays
| | | | there
--------- ---------
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
// Cache selectors outside callback for performance.
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
This simply adds a sticky
CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
#the-sticky-div.sticky {
position: fixed;
top: 0;
}
EDIT- Modified code to cache jQuery objects, faster now.
这篇关于如果向下滚动屏幕,有一个div粘在屏幕的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!