具有声明的宽度和高度的图像在加载前呈现正方形

2023-12-29

我有声明宽度和高度的图像,例如:

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

它们位于响应式网格内,因此它们显示在max-width: 100%。它们是延迟加载的。问题是,尽管有height: auto;,图像始终显示正方形before它们被加载,这会在它们完成加载时造成页面高度的跳跃。

因此,上面的图像示例在我的 960 像素宽度网格中,将显示一个 960 像素 x 960 像素的占位符,直到加载完整图像,此时它将是 960 像素 x Y(其中 Y 是正确的高度)。

我的问题是如何让占位符图像模仿实际图像的最终加载尺寸?


您可以通过以下解决方案达到您想要的效果。

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

Hint:如果您希望占位符矩形可见且采用一种颜色,请考虑使用 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);

Sources:可以找到Lazyload脚本here https://gist.github.com/miloplacencia/3931803.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有声明的宽度和高度的图像在加载前呈现正方形 的相关文章