(注:一下内容是自己通過網絡整理出來的,并非完全自己寫的)
全屏背景是當下比較流行的一種網頁設計風格,而具體的實作這樣的全屏背景無外乎基本就兩種方法,一種的通過CSS去實作的(CSS3.0為我們提供了更為豐富的CSS樣式控制);另一種就是通過我們熟悉的javascript去實作,這裡為了代碼友善就直接使用jQuery了。既然提到jQuery,我們就可以想象既然我們能用jQuery寫了,那網絡上就一定有類似的寫好的jQuery插件等着我們用了。
方法一、利用CSS3.0樣式新特性實作北京全屏(不支援ie6-8)
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
或:
html{
background:url('background.jpg') no-repeat center center;
min-height:100%;
background-size:cover;
}
body{
min-height:100%;
}
原理:将html及body設定為最小高度為100%,使用css3中的background-size:cover;将背景圖檔設定成封面全屏模式。
相容性:
Safari 3+
Chrome Whatever+
IE 9+
Opera 10+
Firefox 3.6+
方法二、使用jQuery實作
HTML代碼:

CSS代碼:
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
jQuery代碼:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
相容性:
IE7+
任何桌面浏覽器
方法二、使用jQuery實作(附)【使用jQuery插件jQuery.fullBg】
具體使用方法在插件位址中有,這裡就不做詳細說明了。
First comes the plugin code:
(function($) {
$.fn.fullBg = function(){
var bgImg = $(this);
function resizeImg() {
var imgwidth = bgImg.width();
var imgheight = bgImg.height();
var winwidth = $(window).width();
var winheight = $(window).height();
var widthratio = winwidth / imgwidth;
var heightratio = winheight / imgheight;
var widthdiff = heightratio * imgwidth;
var heightdiff = widthratio * imgheight;
if(heightdiff>winheight) {
bgImg.css({
width: winwidth+'px',
height: heightdiff+'px'
});
} else {
bgImg.css({
width: widthdiff+'px',
height: winheight+'px'
});
}
}
resizeImg();
$(window).resize(function() {
resizeImg();
});
};
})(jQuery)
There is only a little CSS needed for this one:
.fullBg {
position: absolute;
top: 0;
left: 0;
overflow: hidden;
}
#maincontent {
position: absolute;
top: 0;
left: 0;
z-index: 50;
}
If you want your background to stay fixed you can change the .fullBG CSS to this:
.fullBg {
position: fixed;
top: 0;
left: 0;
overflow: hidden;
}
For the HTML markup, you can just add an image tag with an id or class, but you also need to add a div that contains your main content or else it won’t work properly. This is the bare minimum:
To call the jQuery function, add this to the bottom of your web page, right before the closing body tag:
$(window).load(function() {
$("#background").fullBg();
});
Once again, this plugin is pretty simple so no options are available. It pretty much just does what it does.