以下是 jQuery自适应窗口大小背景js代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery自适应窗口大小背景</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.fullbg.min.js"></script>
<style type="text/css">
.fullBg {
position: fixed;
top: 0;
left: 0;
overflow: hidden;
}
#maincontent {
position: absolute;
top: 300px;
left: 0;
z-index: 50;
width: 100%;
background: #fff;
opacity: 0.9;
filter: alpha(opacity=90);
}
#box {
width: 600px;
margin: auto;
padding: 0 10px;
}
h1 {
margin-top: 12px;
font-size: 40px;
text-align: center;
line-height: 44px;
font-weight: normal;
font-family: Georgia,serif;
color: #222;
}
h2 {
margin-top: 0;
font-size: 24px;
line-height: 28px;
font-weight: normal;
font-family: Georgia,serif;
color: #C52D08;
}
a {
text-decoration: none;
outline: none;
color: #C52D08;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<img src="images/bg.jpg" alt="" id="background" />
<div id="maincontent">
<div id="box">
<h1>Full Size Background Image jQuery Plugin</h1>
<h2>Demo</h2>
Just resize this window and you will see the plugin in action. Whenever the window size changes, the background image size changes. AND it always stays in the proper aspect ratio.
<br>
</div>
</div>
<script type="text/javascript">
$(window).load(function() {
$("#background").fullBg();
});
</script>
</body>
</html>
JS代码(jquery.fullbg.min.js):
/** * jQuery.fullBg * Version 1.0 * Copyright (c) 2010 c.bavota - http://bavotasan.com * Dual licensed under MIT and GPL. * Date:02/23/2010**/
(function($){
$.fn.fullBg=function(){
var bgImg=$(this);
bgImg.addClass('fullBg');
function resizeImg(){
var imgwidth=bgImg.width();
var imgheight=bgImg.height();
var winwidth=$(window).width();
var winheight=$(window).height();
var widthratio=winwidth/imgwidth;
var heightratio=winheight/imgheight;
var widthdiff=heightratio*imgwidth;
var heightdiff=widthratio*imgheight;
if(heightdiff>winheight){
bgImg.css({
width:winwidth+'px',height:heightdiff+'px'}
);
}
else{
bgImg.css({
width:widthdiff+'px',height:winheight+'px'}
);
}
}
resizeImg();
$(window).resize(function(){
resizeImg();
}
);
}
;
}
)(jQuery)