加载背景图像,缩放到窗口大小,然后淡入

时间:2011-11-10 06:26:20

标签: jquery

我最近开始了一个项目,我想让背景图像缩放到窗口的大小。我能够使用以下代码:

<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

2 个答案:

答案 0 :(得分:3)

您可以加载隐藏的图片,调整其大小,然后将其淡入。这种方法要求在客户端启用JavaScript(大约98%的人启用了它,但另一个noscript后退2%可能是值得的)。它看起来像这样(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 :(得分:1)

尝试使用CSS属性max-width: 100%;缩放图像。这个属性很好,因为它不会放大小图像;它只会缩小大图像。图像将立即加载到正确的大小。为什么要为淡化而烦恼呢?

相关问题