把div固定在網頁頂部


很多網站都有把某一塊固定在頂部的功能,今天上網搜搜然后自己又寫了一遍,貼出來給大家看看,哪天用到的時候自己也可以隨時看看

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2   <html xmlns="http://www.w3.org/1999/xhtml">
 3   <head runat="server">
 4       <title></title>
 5       <script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
 6       <script type="text/javascript">
 7           $(function() {
 8               //獲取要定位元素距離瀏覽器頂部的距離
 9               var navH = $(".hb").offset().top;
10               //滾動條事件
11               $(window).scroll(function() {
12                   //獲取滾動條的滑動距離
13                   var scroH = $(this).scrollTop();
14                   //滾動條的滑動距離大於等於定位元素距離瀏覽器頂部的距離,就固定,反之就不固定
15                   if (scroH >= navH) {
16                       $(".hb").css({ "position": "fixed", "top": 0 });
17                   }
18                   else if (scroH < navH) {
19                       $(".hb").css({ "position": "static" });
20                   }
21               })
22           })
23   </script>
24   </head>
25   <body>
26       <div style=" height: 300px;">
27           空div</div>
28       <div class="hb" style="height: 100px; width: 100%; background: #999">
29           移動到頂部固定不變</div>
30       <div style="background: #ccc; height: 1500px;">
31           空div</div>
32   </body>
33   </html>
34 
35 View Code
View Code

西游記告訴我們:凡是有后台的妖怪都被接走了,凡是沒后台的都被一棒子打死了。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM