前幾天無意將QQ空間賬號退出,不經意中看到它的的首頁樣子,說真的,整體看起來真漂亮。后又在無意中縮放瀏覽器大小,看到它的背景圖片會隨着窗體大小和形狀做出不同的縮變,而且沒有一點給人不自然的感覺,這給我這種前端菜鳥看來真是強大啊,所以,菜鳥也想做一個這樣東西。代碼
首先,html是這樣寫的
<body style="overflow: hidden; "> <div id="lay_bg" style="left: 0; position: absolute; top: 0; background-color:#ECFED3;"> <img id="img" src="http://qzs.qq.com/qzone/v6/v6_config/upload/7a082c0dde36eac2205a088397aaf295.jpg" style=" position: absolute;" /> </div> </body>
一個div和img,太簡單了,不解釋了,還有,body中要設置overflow,默認會出現滾動條哦,
當然,重要是js
var cws,chs; window.onload=function(){ resizeBackground(); }; window.onresize = function () { resizeBackground(); }; dom = { getById: function (id) { return document.getElementById(id); }, getClientHeight: function () { return document.documentElement.clientHeight; }, getClientWidth: function () { return document.documentElement.clientWidth; } }; var $ = dom.getById; var resizeBackground= function () { var bg = $('lay_bg'), bg_img = $('img'), cws=cw=dom.getClientWidth()<=cws ? dom.getClientWidth() : dom.getClientWidth(); chs=ch = dom.getClientHeight()<=chs ? dom.getClientHeight() : dom.getClientHeight(); iw = bg_img.width, //圖片width ih = bg_img.height; //圖片height bg.style.width = cw + "px"; bg.style.height = ch + "px"; if (cw / ch > iw / ih) { var new_h = cw * ih / iw, imgTop = (ch - new_h) / 2; bg_img.style.width = cw + "px"; bg_img.style.height = new_h + "px"; bg_img.style.top = imgTop + "px"; bg_img.style.left = ""; } else { var new_w = ch * iw / ih, imgLeft = (cw - new_w) / 2; bg_img.style.width = new_w + "px"; bg_img.style.height = ch + "px"; bg_img.style.left = imgLeft + "px"; bg_img.style.top = ""; } }
這里用到的核心就是通過獲得當前窗體的大小,來調整div大小,同時要兼顧圖片形狀的比例適當調節圖片在div中的位置,
你知道的,首先是窗體改變,當client.width/cilent.height的比例大於圖片的img.width/img.heigth,這樣意味我們在橫向縮小窗體,同時圖片也是橫向縮小,但是如果圖片top不改變的和,圖片不就變形了嗎,所以此時要改變圖片的top位置了,而這種算法是:client.width*img.height/client.height,同時我們又要考慮到圖片要看起來效果往上下兩個方向移動,所以我們把img的top位置在之前的結果上再/2,也就是一半即可。同理當縮小窗體上下的大小時img 的left的屬性算法是:(client.height*img.width/client.width)/2。
嗯,如此這般,這般如此,搞定也。進過多中瀏覽器簡單測試,幾乎不存在瀏覽器兼容問題造成bug,
