最近在制作一個模版的時候用到的一個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