08
2013
07

把某个层固定在网页顶部

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
        <title>
        </title>
        <script src="js/jquery-1.7.1.min.js" type="text/javascript">
        </script>
        <script type="text/javascript">
            $(function() {
                //获取要定位元素距离浏览器顶部的距离
                var navH = $(".hb").offset().top;
                //滚动条事件
                $(window).scroll(function() {
                    //获取滚动条的滑动距离
                    var scroH = $(this).scrollTop();
                    //滚动条的滑动距离大于等于定位元素距离浏览器顶部的距离,就固定,反之就不固定
                    if (scroH >= navH) {
                        $(".hb").css({
                            "position": "fixed",
                            "top": 0
                        });
                    } else if (scroH < navH) {
                        $(".hb").css({
                            "position": "static"
                        });
                    }
                })
            })
        </script>
    </head>
    
    <body>
        <div style=" height: 300px;">
            空div
        </div>
        <div class="hb" style="height: 100px; width: 100%; background: #999">
            移动到顶部固定不变
        </div>
        <div style="background: #ccc; height: 1500px;">
            空div
        </div>
    </body>

«1»