Javascript-元素在滾動條滑動一定高度后自動置頂


 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title></title>
 6     <meta charset="utf-8" />
 7     <style type="text/css">
 8         * { margin: 0; padding: 0; border: 0; }
 9         .top { width: 100%; height: 30px; margin: 0 auto; text-align: center; background-color: #808080; color: #ffffff; margin-bottom: 20px; }
10 
11         .cen, .search, .search li { width: 1200px; height: 40px; margin: 0 auto; }
12         .cen { width: 100%; height: 50px; background-color: #ffffff; z-index: 10; }
13             .cen .search { background-color: #ff6a00; border-radius: 20px; }
14                     .cen .search input { width: 1100px; height: 25px; margin-left: 50px; margin-top: 10px; background: none; outline: none; font-size: 14px; color: #000000; }
15         input::-webkit-input-placeholder { color: #808080; }
16         input:-moz-placeholder { color: #808080; }
17 
18         .con { width: 1200px; height: 1500px; margin: 0 auto; text-align: center; background-color: #ffd800; }
19     </style>
20     <script src="js/jquery-1.10.2.js"></script>
21 </head>
22 
23 <body>
24     <div class="top">頂部內容</div>
25 
26     <div class="cen"><!--這里注意一定要用一個寬100%的外框框起來,否則會影響美觀,整體元素也會在固定置頂時靠左浮動-->
27         <div class="search"><!--這里在用一個寬為1200的元素將內容居中到頁面-->
28             <input type="text" placeholder="請輸入您需要查找的內容..." />
29         </div>
30     </div>
31 
32     <div class="con">頁面內容</div>
33 
34     <script type="text/javascript">
35         //search在滾動條下滑一定高度后固定置頂
36         var titleH = $(".cen").offset().top;                      //獲取滾動條下滑高度(即search固定置頂的條件)
37         $(window).scroll(function () {                                //window滾動條事件
38             var scroH = $(this).scrollTop();                          //獲取滾動條滑動的距離
39             if (scroH > titleH) {                                     //判斷滾動條滑動高度是否大於指定條件高度
40                 $(".cen").css({ "position": "fixed", "top": 0 }); //大於就執行search固定置頂
41             } else if (scroH <= titleH) {                             //小於等於指定條件高度
42                 $(".cen").css({ "position": "static" });          //則就恢復原位
43             }
44         });
45     </script>
46 
47 
48 </body>
49 </html>

 


免責聲明!

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



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