在你的HTML文檔加載jQuery庫直接從谷歌的CDN
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
上面的代碼可以插入您的文檔頭內部的標簽,或在最底層,收盤前體標簽(通常是建議,以獲得更好的性能)。
添加背景圖片的標記
<div id="bg">
<img src="image-name.jpg" width="1280" height="800" id="bgimg" />
</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>