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

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

smohan.fixednav.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * 随滚动条固定导航到顶部插件
 * 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)

使用方法:

1
2
3
4
5
6
7
<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 @   panie2015  阅读(8235)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示