使用jquery和css快速实现置顶导航条
使用jQuery和css可以快速简单实现固定在页面顶端的导航区块效果,默认导航区块正常显示,当用户向下拖动滚动条时,导航区块会始终固定在页面顶端显示,保证用户一直能看到导航区块。
CSS代码:
.sticky { position: fixed; width: 100%; left: 0; top: 0; z-index: 999; border-top: 0; }
javascript代码:
$(document).ready(function() { // grab the initial top offset of the navigation bar var stickyBarTop = $('.navbar').offset().top; // decides weather the navigation bar should have "fixed" css position or not. var stickyBar = function(){ // current vertical position from the top var scrollTop = $(window).scrollTop(); // if scrolled more than the navigation, change its position to fixed to stick to top, // otherwise change it back to relative if (scrollTop > stickyBarTop) { $('.navbar').addClass('sticky'); } else { $('.navbar').removeClass('sticky'); } }; stickyBar(); // run it again every time you scroll $(window).scroll(function() { stickyBar(); }); });
HTML代码:
<div class="wrapper"> <div class="header">Header</div> <div class="navbar">Navigation bar</div> <div class="content"><p>main content ...</p></div> </div>
其他固顶jquery插件:
https://github.com/bigspotteddog/ScrollToFixed
10月 8, 2014 | In: 网页