Emi*_*ero 4 jquery background image
我需要一个简单的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');
});
});
Run Code Online (Sandbox Code Playgroud)
像这样设置你的HTML
<div id="page">
Your page contents here..
</div>
<div id="background-container">
<img src="path/to/image" />
</div>
Run Code Online (Sandbox Code Playgroud)
和你的CSS一样
#background-container{
position:absolute;
z-index:1;
top:0;
left:0;
width:100%;
height:100%;
overflow:hidden;
}
#page{
position:relative;
z-index:5;
}
Run Code Online (Sandbox Code Playgroud)
演示 http://jsfiddle.net/gaby/3YLQf/