元素position設定為fixed而未指定top、bottom、left、right時的定位
阿新 • • 發佈:2019-01-22
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>fixed定位</title> <style type="text/css"> * {margin:0; padding:0; border:0;} #wrapper {width:1000px; height:2000px; margin: 0 auto;} #div1 {height:100px; background-color:red;} #div21 {width:100px; height:200px; background-color:blue; padding:10px; border:5px solid black;} #div22 {width:50px; height:100px; background-color:#0F0; position:static; float:right;} </style> <script> window.onscroll = function () { var scrollTop = document.documentElement.scrollTop; if(scrollTop > 115){ document.getElementById("div22").style.position = "fixed"; } else { document.getElementById("div22").style.position = "static"; } } </script> </head> <body> <div id="wrapper"> <div id="div1"></div> <div id="div21"> <div id="div22"></div> </div> </div> </body> </html>
當一個元素的position被設定為fixed,而top、bottom、left、right未指定時:
水平方向,元素會靠在父元素的內左邊緣;
垂直方向,元素離瀏覽器視窗上邊緣的距離,為頁面開啟時該元素離瀏覽器視窗上邊緣的距離。