14

幅と高さが宣言された画像があります。

<img src="foo.jpg" width="1500" height="1800" alt="bar" />

それらはレスポンシブ グリッド内にあるため、 に表示されmax-width: 100%ます。それらは遅延ロードされますheight: auto;

したがって、上記の画像の例では、私の 960px 幅のグリッドでは、完全な画像が読み込まれるまで 960px x 960px でプレースホルダーが表示され、その時点で 960px x Y (Y は正しい高さ) になります。

私の質問は、実際の画像の最終的に読み込まれた寸法を模倣するプレースホルダー画像を取得するにはどうすればよいですか?

4

6 に答える 6

4

次のソリューションで目的の効果を得ることができます。

HTML:

<img src="blank.gif" class="lazy" data-src="foo.png" width="1500" height="1800" alt="bar">  
             ▲                ▲  
             ║                ╚═══ The class will be used for the lazy loader below  
             ║  
             ╚═══ Use faulty gif here to hide it from showing before loaded

ヒント: プレースホルダーの四角形を 1 色で表示したい場合は、 に 1x1 ピクセルの画像を使用することを検討してblank.gifください。それは非常に速くロードされ、あなたのプロポーションにうまく伸び、選択した色で塗りつぶされます.

JavaScript:

/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:  
 * `<img src="blank.gif" data-src="my_image.png" width="600" height="400" class="lazy">`
 */

!function(window){
  var $q = function(q, res){
        if (document.querySelectorAll) {
          res = document.querySelectorAll(q);
        } else {
          var d=document
            , a=d.styleSheets[0] || d.createStyleSheet();
          a.addRule(q,'f:b');
          for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)
            l[b].currentStyle.f && c.push(l[b]);

          a.removeRule(0);
          res = c;
        }
        return res;
      }
    , addEventListener = function(evt, fn){
        window.addEventListener
          ? this.addEventListener(evt, fn, false)
          : (window.attachEvent)
            ? this.attachEvent('on' + evt, fn)
            : this['on' + evt] = fn;
      }
    , _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      }
    ;

  function loadImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-src');
    img.onload = function() {
      if (!! el.parent)
        el.parent.replaceChild(img, el)
      else
        el.src = src;

      fn? fn() : null;
    }
    img.src = src;
  }

  function elementInViewport(el) {
    var rect = el.getBoundingClientRect()

    return (
       rect.top    >= 0
    && rect.left   >= 0
    && rect.top <= (window.innerHeight || document.documentElement.clientHeight)
    )
  }

    var images = new Array()
      , query = $q('img.lazy')
      , processScroll = function(){
          for (var i = 0; i < images.length; i++) {
            if (elementInViewport(images[i])) {
              loadImage(images[i], function () {
                images.splice(i, i);
              });
            }
          };
        }
      ;
    // Array.prototype.slice.call is not callable under our lovely IE8 
    for (var i = 0; i < query.length; i++) {
      images.push(query[i]);
    };

    processScroll();
    addEventListener('scroll',processScroll);

}(this);

ソース: Lazyload スクリプトはここにあります。

于 2014-03-24T17:19:27.037 に答える
0

ここで私はあなたのためにフィドルを作りました

主なことは、その周りに div を生成し、ロード後に必要に応じて高さと幅を設定することです。その後、そのコンテナ内にロードすることができ、スムーズな効果も得られます ;)

HTML

<div class="site-wrapper">
    <div class="lazyload" data-src="http://tinyurl.com/py2nunk" data-width="1920" data-height="1200"></div>
</div>

CSS

.site-wrapper {
    width:960px;
}
.lazyload {
    max-width: 100%;
    border: 1px solid #000;
}
.lazyload img {
    max-width: 100%;
}

ジャバスクリプト

$(document).ready(function() {
    $('.lazyload').each(function() {
        var parentwidth = $(this).parent().width();
        var width  = $(this).attr('data-width');    
        var height = $(this).attr('data-height');

        if(parentwidth < width) {
            height = (parentwidth/width*height);
            width = parentwidth;
        }

        $(this).css({ width: width+'px', height: height+'px'});

    });

    // simulating lazyload
    setTimeout(function() {
        $('.lazyload').each(function() {
            img = $('<img>', { 'class': 'lazyloaded' }).css({display: 'none'});
            original = $(this);
            $(img).load( function(){
                original.append(img);
                $(this).fadeIn(200);
            }).attr('src', $(this).attr('data-src'));
        });
    }, 5000);
});

これが必要かどうかをお知らせください。必要に応じて変更できます。

于 2014-03-24T17:17:55.390 に答える
0

css で画像に必要な最大高さを追加してください。これで問題が解決すると思います。

于 2014-03-31T12:02:24.213 に答える