大家都知道,當position的值為fix時,生成絕對定位的元素,相對於瀏覽器窗口進行定位。
它常常應用的場合是,當下拉滾動條時固定導航欄到頂部,將廣告固定在頁面兩側或瀏覽器中間。
如果需要將導航欄div固定到瀏覽器頂部,只需要將top設置為0即可。
如果要將廣告div固定在特定位置,只需要用js計算出div應顯示的位置,再設置top和left屬性。
當我們想要設置一個div相對於其父元素定位,大家一定會想,將父元素position設置為relative,子元素為absolute不就可以了嗎?
但有些時候,我們想要這個div相對父元素定位,要想保留fix定位的一些特征。比如,一個父容器下有一個div,我們想將這個div固定在父容器的頂部(而不是整個瀏覽器的頂部),當拉動滾動條時它的位置不發生變化,這時應該怎么做呢

如上圖,我們想實現的效果是,紅色部分固定在content的頂部位置,實現代碼為
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> 6 <title> 頁面名稱 </title> 7 <style type="text/css"> 8 html, body { 9 margin: 0; 10 padding: 0; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="par" style='margin-top:150px;background-color:blue; position: relative;height:1500px'> 16 <div id="fix" style="position: absolute;top:0px;left:60px;width:180px;background-color:red;"> 17 這個是固定的DIV 18 </div> 19 20 </div> 21 <script type="text/javascript"> 22 window.onscroll = function () { 23 var fix = document.getElementById("fix"); 24 var par = document.getElementById("par"); 25 var st = document.documentElement.scrollTop || document.body.scrollTop; 26 var pt = par.offsetTop; 27 fix.style.position = st>pt ? "fixed" : "absolute"; 28 } 29 </script> 30 </body> 31 </html>
還有一種存在左側導航欄的情況

實現代碼為
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> 6 <title> 頁面名稱 </title> 7 <script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.js"></script> 8 <style type="text/css"> 9 html, body { 10 margin: 0; 11 padding: 0; 12 } 13 </style> 14 </head> 15 <body> 16 <div> 17 <div style="width:100%;height: 100px; background-color: #ccc;"> 18 </div> 19 <div> 20 <div style="width:20%;height:100%;background-color: #bbb;float: left">333333333333</div> 21 <div id="par" style=' float: left; width:80%;background-color:blue; position: relative;height: 1500px'> 22 <div id="fix" style="position: absolute;top:0px;left:0px;width:100%;background-color:red;height:100px"> 23 這個是固定的DIV 24 </div> 25 26 <div id='ct' style="margin-top: 120px"> 27 </div> 28 29 </div> 30 31 </div> 32 33 34 </div> 35 36 <script type="text/javascript"> 37 window.onscroll = function () { 38 var fix = document.getElementById("fix"); 39 var par = document.getElementById("par"); 40 //var sp = document.getElementById("sp"); 41 var ct = document.getElementById("ct"); 42 var st = document.documentElement.scrollTop || document.body.scrollTop; 43 var pt = par.offsetTop; 44 if (st>pt) { 45 fix.style.left = par.offsetLeft + "px"; 46 fix.style.width = par.offsetWidth + "px"; 47 fix.style.position = "fixed"; 48 var top = (document.documentElement.scrollTop - 200 + 120) + 'px'; 49 console.log(top); 50 $(ct).css('margin-top','120px'); 51 } else { 52 fix.style.left = "0px"; 53 fix.style.width = "100%"; 54 fix.style.position = "absolute"; 55 } 56 } 57 </script> 58 </body> 59 </html>
