【问题标题】:Load background image, scale to window size, then fade in加载背景图像,缩放到窗口大小,然后淡入
【发布时间】:2011-11-10 14:52:25
【问题描述】:

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

<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

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以加载隐藏的图像,调整其大小,然后将其淡入。这种方法需要在客户端启用 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 已准备好以及此特定图像是否已完成加载。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 您案例的完整 CSS 代码为 img#bg { max-width:100%; }
      • 我认为如果图像在加载后淡入会更好看。 For example.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多