使用JQuery的全屏背景图片,自动适应各种屏幕和浏览器

在你的HTML文档加载jQuery库直接从谷歌的CDN

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

上面的代码可以插入您的文档头内部的标签,或在最底层,收盘前体标签(通常是建议,以获得更好的性能)。

添加背景图片的标记

<div >
    <img src="image-name.jpg" width="1280" height="800"  />
</div>

更改源属性图像name.jpg映像路径和设置它的实际宽度和高度属性。

图像容器的CSS:

body{margin:0px; padding:0px; background:#000;}
#bg{position:fixed; z-index:1; overflow:hidden;}

接下来,我们需要插入一切工作的中心STRECHING proportionaly我们的形象,它的??实际功能。所以在jQuery的夹杂物插入:

<script type="text/javascript">
function FullScreenBackground(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var imageWidth=$(theItem).width();
var imageHeight=$(theItem).height();
var picHeight = imageHeight / imageWidth;
var picWidth = imageWidth / imageHeight;
if ((winHeight / winWidth) < picHeight) {
$(theItem).css("width",winWidth);
$(theItem).css("height",picHeight*winWidth);
} else {
$(theItem).css("height",winHeight);
$(theItem).css("width",picWidth*winHeight);
};
$(theItem).css("margin-left",winWidth / 2 - $(theItem).width() / 2);
$(theItem).css("margin-top",winHeight / 2 - $(theItem).height() / 2);
}
</script>

此功能使图像的宽度和高度伸展,这取决于浏览器和图像尺寸比例。

最后,插入的功能,来检查时,我们的页面加载和浏览器的大小:

<script type="text/javascript">
window.onload = function () {
FullScreenBackground('#bgimg');
}
$(window).resize(function() {
FullScreenBackground('#bgimg');
});
</script>