想要一張「永遠貼齊視窗、不會變形、捲動時不動」的背景圖,看似簡單,但要在舊版 IE 上也成立,就得動一些手腳。這份範例的策略有三點:背景圖固定、隨視窗大小縮放、縮放時保持原始比例。
body{margin:0; padding:0; height:2000px; }
#background_img{
top: expression(documentElement.scrollTop); /* IE6 靠 expression 模擬 fixed */
}
IE6 不支援 position:fixed,只能靠 CSS expression 讓元素在捲動時持續貼齊頂部。這是歷史包袱,也是這份程式需要額外判斷瀏覽器的原因。
/**
* @desc 製作固定背景圖,縮放以符合視窗大小,且不破壞圖片比例
* @author EI Nino
* 2013/8/15
*/
var imgBackground = function(_img_obj) {
this.img = _img_obj;
this.init();
}
imgBackground.prototype = {
init: function(){
this.img.style.top = "0";
this.img.style.left = "0";
if(navigator.appVersion.indexOf('MSIE 6.0') > 0){
this.img.style.position = "absolute";
this.img.style.bottom = "auto";
// 避免 IE6 捲動時背景閃爍
if(!document.body.style.backgroundImage){
document.body.style.backgroundImage = "url(about:blank)";
document.body.style.backgroundAttachment = "fixed";
}
} else {
this.img.style.position = "fixed";
}
this.ra = this.img.width / this.img.height; // 記錄原始寬高比
this.resize();
this.BindEvent();
},
resize: function() {
var self = this;
if((document.documentElement.clientWidth /
document.documentElement.clientHeight) >= self.ra) {
// 視窗較寬:以寬度為基準
self.img.style.width = document.documentElement.clientWidth + "px";
self.img.style.height = "";
} else {
// 視窗較高:以高度為基準
self.img.style.width = "";
self.img.style.height = document.documentElement.clientHeight + "px";
}
},
GetStyle: function(_obj, _style){
var obj = _obj;
return obj.currentStyle ? obj.currentStyle[_style]
: window.getComputedStyle(obj, null)[_style];
},
BindEvent: function(){
var self = this;
$(window).resize(function(){ // 使用 jQuery
self.resize();
});
}
};
new imgBackground(document.getElementById("background_img"));
整段程式最聰明的地方在 resize()。它先算出圖片的原始寬高比 ra = width / height,再拿視窗的寬高比跟它比較:
width、把 height 清空讓它自動等比。height。因為永遠只主導一個維度,另一維度交給瀏覽器依原始比例計算,圖片自然不會變形,同時還能保證完整覆蓋視窗(也就是後來說的「cover」行為)。
這份程式寫於 2013 年,當時 CSS 還做不到這件事。現在的 answer 是 background-size:
body {
margin: 0;
background-image: url(bg.jpg);
background-size: cover; /* 等比縮放並填滿,不變形 */
background-position: center; /* 置中 */
background-attachment: fixed; /* 捲動時固定 */
background-repeat: no-repeat;
}
cover 的行為與上面的 resize() 邏輯完全一致——等比放大到能覆蓋整個容器為止。若想改用 <img> 標籤以便做 SEO 或 srcset,則可以:
img {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
object-fit: cover 是 img 版本的同一招,一行取代原本整個建構式。
這個案例的價值不在程式碼本身(它已被 CSS 標準取代),而在解題思路:把「填滿且不變形」拆解成「比較兩個寬高比,每次只主導一個維度」。這個思路在任何需要手動計算等比縮放的場合都還通用。