我前一阵子这样做了,这是我为此创建的代码:查看 JSFiddle。
(您可能需要稍微更改您的标记,我不确定这与您拥有的表格布局的效果如何,我建议使用divs
并浮动它们来布局您的内容。),或者,您可以使用代码/下面的逻辑和roll your own
你自己的布局。
基本上,
- 获取我们的元素
- 获取侧边栏在页面加载时的位置
- 获取#content.outerHeight()
一旦我们有了这些变量,在window scroll
测试中查看我们是否<=
(小于或等于)我们的原始变量sidebarTop position
或检查我们是否超过了blogHeight
,如果有任何关闭 2 为真,删除粘性类,elseif
我们的滚动是>=
我们的原始sidebar
位置,然后添加.sticky
类(具有position: fixed
)。
检查 JSFiddle (点击这里)
Javascript是这样的:
// Cache our vars for the fixed sidebar on scroll
var $sidebar = $('#sidebar-nav');
// Get & Store the original top of our #sidebar-nav so we can test against it
var sidebarTop = $sidebar.position().top;
// Edit the `- 10` to control when it should disappear when the footer is hit.
var blogHeight = $('#content').outerHeight() - 10;
// Add the function below to the scroll event
$(window).scroll(fixSidebarOnScroll);
// On window scroll, this fn is called (binded above)
function fixSidebarOnScroll(){
// Cache our scroll top position (our current scroll position)
var windowScrollTop = $(window).scrollTop();
// Add or remove our sticky class on these conditions
if (windowScrollTop >= blogHeight || windowScrollTop <= sidebarTop){
// Remove when the scroll is greater than our #content.OuterHeight()
// or when our sticky scroll is above the original position of the sidebar
$sidebar.removeClass('sticky');
}
// Scroll is past the original position of sidebar
else if (windowScrollTop >= sidebarTop){
// Otherwise add the sticky if $sidebar doesnt have it already!
if (!$sidebar.hasClass('sticky')){
$sidebar.addClass('sticky');
}
}
}
的HTML:
<header>This is the header!</header>
<ul id="sidebar-nav" class="nav nav-list">
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
</ul>
<div id="content">Content in here, scroll down to see the sticky in action!</div>
<div class="clear"></div>
<div id="footer">This is the #footer</div>
的CSS:
/* Sticky our navbar on window scroll */
#sidebar-nav.sticky {position:fixed;top:5px;}
/* Other styling for the html markup */
header {
border:1px solid #aaa;
background-color:yellow;
margin-bottom:5px;
height:50px;
}
#sidebar-nav {
width:150px;
border:1px solid #ddd;
margin:0;
padding:0;
float:left;
}
#sidebar-nav li {
list-style:none;
border:1px solid #ddd;
margin:10px;
padding:2px;
}
#content {
height:2000px;
width:500px;
padding:10px;
border:1px solid #ddd;
margin:0 0 10px 5px;
float:right;
}
#footer {
height:800px;
border:1px solid green;
background-color:#ddd;
}
.clear {
clear:both;
}
:)