我需要一个简单的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;
}
Demo at http://jsfiddle.net/gaby/3YLQf/
$document = $(document);
改成 $document = $(window);
。 - Gabriele Petrioli或者你可以使用CSS属性:
background-size: cover
这将按比例缩放图像,以使其完全覆盖背景定位区域的宽度和高度,并保留其固有的长宽比(如果有)。
您可以使用background-position
属性控制图像在视口中的对齐方式。
background-position: 50% 50%
就可以了。 - Ahmad Alfy