網站上的客服視窗、公告小窗,通常都要固定在視窗的某個角落,不隨頁面捲動而跑掉。本文示範如何以 CSS 定位搭配一小段 JavaScript,做出一個黏在右下角的懸浮視窗,並在視窗尺寸改變時自動重新填滿可用空間。
<!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>Fixed固定位置的懸浮</title> <style> * { font-size:12px; font-family:Verdana,宋體; } html, body { margin:0px; padding:0px; overflow:hidden; } .b { margin:0px; padding:0px; overflow:auto; } .line0 { line-height:20px; background-color:lightyellow; padding:0px 15px; } .line1 { line-height:18px; background-color:lightblue; padding:0px 10px; } .w { position:absolute; right:10px; bottom:10px; width:160px; height:240px; overflow:hidden; border:2px groove #281; cursor:default; -moz-user-select:none; } .t { line-height:20px; height:20px; width:160px; overflow:hidden; background-color:#27C; color:white; font-weight:bold; border-bottom:1px outset blue; text-align:center; } .winBody { height:218px; width:160px; overflow-x:hidden; overflow-y:auto; border-top:1px inset blue; padding:10px; text-indent:10px; background-color:white; } </style> </head> <body> <div class="w"> <div class="t">Demo Win - Fixed</div> <div class="winBody">Hello world</div> <div>https://www.jb51.net/</div> </div> </body> <script> //測試用,隨機產生一定的內容 for(var i=0; i<400; i++)document.write("<div class=\"line"+(i%2)+"\">"+(new Array(20)).join((Math.random()*1000000).toString(36)+" ")+"<\/div>"); //代碼如下: new function(w,b,c,d,o){ d=document;b=d.body;o=b.childNodes;c="className"; b.appendChild(w=d.createElement("div"))[c]= "b"; for(var i=0; i<o.length-1; i++)if(o[i][c]!="w")w.appendChild(o[i]),i--; (window.onresize = function(){ w.style.width = d.documentElement.clientWidth + "px"; w.style.height = d.documentElement.clientHeight + "px"; })(); } </script> </html>
最外層的 .w 使用 position: absolute 搭配 right 與 bottom,就能把視窗釘在右下角。標題列 .t 固定 20 像素高、內容區 .winBody 則給予固定高度並開啟垂直捲軸,讓視窗在內容過多時不會撐破版面。
那段看似壓縮得很緊的立即執行函式,做了三件事:建立一個新的容器 div、把原本的 body 子節點搬進去、最後在 onresize 中把這個容器的寬高設為 clientWidth/clientHeight。這樣做的用意是替頁面加上一層「可捲動的內容殼」,讓懸浮視窗能穩定地相對可視區域定位,而不受下方長內容影響。
純 CSS 其實也能達到類似效果,但舊版瀏覽器對 position: fixed 支援不一,因此過去常以 absolute 加上 JS 補償。今日若只需固定定位,直接使用 position: fixed 即可;上述的 onresize 同步技巧,在需要動態計算可用寬高的自適應版面中仍然很實用。