[英]full page background image resizable - maintain aspect-ratio
我需要一個簡單的jquery解決方案,將背景圖像添加到我的頁面中,完全填充它,但保持縱橫比和垂直和水平居中位置。
這里有幾個插件,但我不想使用任何插件。
提前致謝。
這段代碼會做你想要的......
$(function(){
var stretcher = $('#background-container > img'),
element = stretcher[0],
currentSize = { width: 0, height: 0 },
$document = $(document);
$(window).resize(function () {
var w = $document.width();
var h = $document.height();
if (currentSize.width != w || currentSize.height != h) {
stretcher.width(w).height('auto');
if (h > element.height) {
stretcher.width('auto').height(h);
}
currentSize.width = w;
currentSize.height = element.width;
}
})
$(window).load(function () {
$(this).trigger('resize');
});
});
像這樣設置你的HTML
<div id="page">
Your page contents here..
</div>
<div id="background-container">
<img src="path/to/image" />
</div>
和你的CSS一樣
#background-container{
position:absolute;
z-index:1;
top:0;
left:0;
width:100%;
height:100%;
overflow:hidden;
}
#page{
position:relative;
z-index:5;
}
或者您可以使用CSS屬性:
background-size: cover
這將縮放圖像,同時保持其固有的寬高比(如果有的話)到最小尺寸,使得其寬度和高度都可以完全覆蓋背景定位區域。
您可以使用background-position
屬性控制圖像在視口中的對齊方式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.