[英]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.