2011-11-10 27 views
1

我最近启动了一个项目,我想让背景图像缩放到窗口的大小。我能使其与下面的代码工作:加载背景图像,缩放到窗口大小,然后淡入

<script> 
$(window).load(function() {  

     var theWindow  = $(window), 
      $bg    = $("#bg"), 
      aspectRatio  = $bg.width()/$bg.height(); 

     function resizeBg() { 

       if ((theWindow.width()/theWindow.height()) < aspectRatio) { 
        $bg 
         .removeClass() 
         .addClass('bgheight'); 
       } else { 
        $bg 
         .removeClass() 
         .addClass('bgwidth'); 
       } 

     } 

     theWindow.resize(function() { 
       resizeBg(); 
     }).trigger("resize"); 

}); 

</script> 
</head> 
<body> 
    <img src="images/ij_background.jpg" id="bg" alt=""> 
</body> 
</html> 

的问题是,背景图像将加载完整大小的图片,然后扩展到窗口的大小,这是一个有点难看。我希望图像加载,缩放,然后用淡入淡出来显示。因为我对jQuery有点新鲜感,所以我变得有点卡住了。这里是我有so far

回答

3

您可以加载图像隐藏,调整大小,然后淡入。此方法要求在客户端上启用JavaScript(约98%的人启用了该功能,但其他2%的noscript回退可能会是值得的)。它看起来像这样(live copy):

// jQuery 
jQuery(function($) { 
    var theWindow  = $(window), 
     aspectRatio, 
     // Create img element in jQuery wrapper 
     $bg    = $("<img>"), 
     // Get the raw element 
     bg    = $bg[0]; 

    // Hide the element, hook its load event, and set its `id` and `src` 
    // Important: Hook the load event *before* setting `src` 
    $bg.hide().load(bgLoad); 
    bg.id = "bg"; 
    bg.src = "http://www.injurytimeshort.lanewaypictures.com/images/ij_background.jpg"; 

    // Append it to the body 
    $bg.appendTo(document.body); 

    // Resize on window resize 
    theWindow.resize(resizeBg); 

    function bgLoad() { 
    // Now that the image is loaded, get its aspect ratio 
    aspectRatio = $bg.width()/$bg.height(); 

    // Resize it 
    resizeBg(); 

    // And fade it in 
    $bg.fadeIn(); 
    } 

    function resizeBg() { 

     if ((theWindow.width()/theWindow.height()) < aspectRatio) { 
      $bg 
       .removeClass() 
       .addClass('bgheight'); 
     } else { 
      $bg 
       .removeClass() 
       .addClass('bgwidth'); 
     } 

    } 
}); 

请注意,我们不再等待整体window#load事件,火灾,我们只关心的是,DOM已准备就绪,这个特定的图像加载完成。

1

尝试缩放带有CSS属性max-width: 100%;的图像。这个属性很好,它不会放大小图像;它只会缩小大图像。图像将立即以正确的大小加载。为什么要打扰淡入淡出?

+0

您的案例的完整CSS代码将是'img#bg {max-width:100%; }' –

+0

我认为如果图像在加载后会淡入,它会更好看。 [例如。](http://www.thepra.com.au/) – BobSacamano

+0

哦,那看起来不错! –