jq-demo-2种吸顶效果
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 #box2 { 8 width: 100%; 9 height: 60px; 10 background: rgba(222,222,100, 0.6); 11 } 12 </style> 13 <script src="js/jquery-1.12.3.js"></script> 14 <script> 15 $(function(){ 16 17 var box2Top = $("#box2").offset().top; 18 console.log(box2Top); 19 20 //页面滚动 21 $(window).scroll(function(){ 22 var scrollTop = $(window).scrollTop(); 23 24 if (scrollTop >= box2Top) { 25 $("#box2").css({"position": "fixed", top:0}); //固定定位 26 } 27 else { 28 $("#box2").css({position: "static"}); 29 } 30 31 }) 32 33 }) 34 </script> 35 </head> 36 <body> 37 <div id="box1">box1 38 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 39 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 40 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 41 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 42 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 43 </div> 44 <div id="box2">box2</div> 45 <div id="box3"> box3 46 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 47 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 48 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 49 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 50 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 51 </div> 52 </body> 53 </html>
效果2
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 #box3 { 8 width: 100%; 9 height: 60px; 10 background: rgba(222,222,100, 0.6); 11 position: fixed; 12 top: 0; 13 display: none; 14 } 15 </style> 16 <script src="js/jquery-1.12.3.js"></script> 17 <script> 18 $(function(){ 19 20 $(window).scroll(function(){ 21 var scrollTop = $(window).scrollTop(); 22 23 if ( scrollTop >= $("#box2").offset().top ) { 24 $("#box3").fadeIn(); //淡入 25 } 26 else { 27 $("#box3").fadeOut(); //淡出 28 } 29 }) 30 31 }) 32 </script> 33 </head> 34 <body> 35 <div id="box1">box1 36 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 37 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 38 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 39 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 40 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 41 </div> 42 <div id="box2">box2 43 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 44 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 45 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 46 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 47 <p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p> 48 </div> 49 <div id="box3">box3</div> 50 </body> 51 </html>