我需要一个简单的jquery解决方案,将背景图像添加到我的页面中,完全填充它,但保持纵横比和垂直和水平居中位置。
这里有几个插件,但我不想使用任何插件。
提前感谢。
答案 0 :(得分:8)
此代码可以满足您的需求..
$(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;
}
答案 1 :(得分:4)
或者您可以使用CSS属性:
background-size: cover
这将缩放图像,同时保持其固有的宽高比(如果有的话)到最小尺寸,使其宽度和高度都可以完全覆盖背景定位区域。
您可以使用background-position
属性