jquery实现导航栏跟随窗口滚动

最近在制作一个模版的时候用到的一个jquery插件,当网站导航滚动到当前可见页面顶部时,固定在顶部并随窗口滚动,有很多的网站前台模版有有类似的效果。

smohan.fixednav.js

/*
 * 随滚动条固定导航到顶部插件
 * autho:Smohan
 * http://www.smohan.net
 */
;
(function ($) {
	$.fn.smohanfixednav = function (mtop, zindex) {
		var nav = $(this),
		isIE6 = 'undefined' == typeof(document.body.style.maxHeight),
		mtop = mtop,
		zindex = zindex,
		dftop = nav.offset().top - $(window).scrollTop(),
		dfleft = nav.offset().left - $(window).scrollLeft(),
		dfcss = new Array;
		dfcss[0] = nav.css("position"),
		dfcss[1] = nav.css("top"),
		dfcss[2] = nav.css("left"),
		dfcss[3] = nav.css("zindex"),
		$(window).scroll(function (e) {
			$(this).scrollTop() > dftop ? isIE6 ? nav.css({
				position : "absolute",
				top : eval(document.documentElement.scrollTop),
				left : dfleft,
				"z-index" : zindex
			}) : nav.css({
				position : "fixed",
				top : mtop + "px",
				left : dfleft,
				"z-index" : zindex
			}) : nav.css({
				position : dfcss[0],
				top : dfcss[1],
				left : dfcss[2],
				"z-index" : dfcss[3]
			})
		})
	}
})(jQuery)

 注: 由于jquery的1.9 以上的版本,不再支持 $.browser 方法。所以将原有插件中判断是否是IE6 的语句 $.browser.msie&&$.browser.version=="6.0" 改为 'undefined' == typeof(document.body.style.maxHeight)

使用方法:

<script type="text/javascript" src="/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="smohan.fixednav.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$('.mainavi').smohanfixednav(0,999);
});
</script>

  

1、(0,999)两个数值,第一个一个是设置在滚动时导航栏与顶部的距离,第二个是导航栏的zindex

2、mainavi 为导航栏的class

posted @ 2016-06-22 16:58  panie2015  阅读(8211)  评论(0编辑  收藏  举报