2013-07-29 160 views
0

我有一个问题。 我想要一个宽度为100%窗口的div容器中的背景图像。 我希望它在变焦时发生变化,当我调整窗口大小时它应该调整大小。jQuery的背景图像缩放或窗口调整大小

这里是我的尝试:

var imageWidth = 1024; 
 
var imageHeight = 600; 
 

 
$(document).ready(function(){ 
 
    jQuery(window).resize(function(){ 
 
     resizeImage(); 
 
     api.reinitialise(); 
 
    } 
 
} 
 

 
$(window).resize(function() {resizeImage()}); 
 

 
function resizeImage() { 
 
var navWidth = jQuery(window).width(); 
 
var navHeight = jQuery(window).height(); 
 
var navRatio = navWidth/navHeight; 
 
var imageRatio = imageWidth/imageHeight; 
 
if (navRatio > imageRatio) { 
 
    var newHeight = (navWidth/imageWidth) * imageHeight; 
 
    var newWidth = navWidth; 
 
} else { 
 
    var newHeight = navHeight; 
 
    var newWidth = (navHeight/imageHeight) * imageWidth; 
 
} 
 
var newTop = 0 - ((newHeight - navHeight)/2); 
 
var newLeft = 0 - ((newWidth - navWidth)/2); 
 
$('#image').css({height: navHeight, width: navWidth}); 
 
$('#image img').css({height: newHeight, width: newWidth, top: newTop, left: newLeft}); 
 
$('#image').css({visibility:"visible", display:"block"}); 
 
}
img { border:0px; } 
 
html { height:100%; } 
 
body { width: 100%; height: 100% ; text-align:left; font: normal 12px Arial} 
 
div#image {position:fixed; z-index:98; display:block;} 
 
div#image img {overflow:hidden; position:absolute; z-index:99;}
<head> 
 
    <link rel="stylesheet" href="style.css" type="text/css" media="screen" /> 
 
    <script type="text/javascript" src="test.js"></script> 
 
</head> 
 
<body> 
 
    <div id="image"><img src="http://www.cdelit.com/images/rocketlauncher/frontpage/showcase/img2.png" alt="" /></div> 
 
</body>

现在的问题是,该图像调整到错误的大小。

+0

问题是什么/问题? –

回答

1

你知道你可以通过多种方式使用css(3)来实现吗? http://css-tricks.com/perfect-full-page-background-image/

html { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
    } 
+0

非常感谢你 –

+0

唯一的问题是那些不支持css3的用户 –

+0

对于大多数兼容性来说,你需要使用提供的jQuery方法 –

0
$(window.innerWidth).on('change', function(){ 

}); 
相关问题