只要運用 CSS 的固定定位,就能輕鬆做出懸浮效果(例如常見的對聯廣告),完全不必動用 JavaScript——在樣式中寫上一句 position:fixed; 即可。
由於 position:fixed; 以視窗作為包含塊,元素會固定停留在瀏覽器視窗內。
然而 IE 6.0 並不支援這個屬性,因此實務上要改用相對於 html 元素的絕對定位來變通處理。
完整程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>CSS固定定位</title>
<style type="text/css">
* {
padding:0;
margin:0;
}
#fixedLayer {
width:100px;
line-height:50px;
background: #FC6;
border:1px solid #F90;
position:fixed;
left:10px;
top:10px;
}
</style>
<!--[if lte IE 6]>
<style type="text/css">
html {
height:100%;
overflow:hidden;
}
body {
height:100%;
overflow:auto;
}
#fixedLayer {
position:absolute;
}
</style>
<![endif]-->
</head>
<body>
<div id="fixedLayer">固定不動</div>
<p>dd</p>
<p>dd</p>
<p>dd</p>
<p>dd</p>
<p>dd</p>
<p>dd</p>
<p>dd</p>
(其後重複多個相同的 <p>dd</p>,用以撐出可滾動的長頁面)
</body>
</html>
