首页 > 技术文章 > div总在页面最顶端

mengxingxinqing 2013-07-03 10:27 原文

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="菜单栏在页面顶部.WebForm1" %>

<!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="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(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>
    <form id="form1" runat="server">
    <div class="hb" style="height:100px;width:100%;background:#9966FF">移动到顶部固定不变</div>  
    <div style="background:#003366;height:500px;">空div</div>  
    
    <div style="background:#ff0000;height:1500px;">空div</div>  
    <div style="background:#ccc;height:1500px;">空div</div>  
    
    </form>
</body>
</html>


  

 

推荐阅读