html – 声明宽度和高度的图像在加载前呈现方形

前端之家收集整理的这篇文章主要介绍了html – 声明宽度和高度的图像在加载前呈现方形前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的图像具有声明的宽度和高度,例如:
<img src="foo.jpg" width="1500" height="1800" alt="bar" />

它们位于响应式网格内,因此它们以最大宽度显示:100%.它们是懒惰的.问题是,尽管有height:auto;图像在加载之前总是显示正方形,当它们加载完成时会在页面高度上产生跳跃.

所以上面的图像示例,在我的960px宽度网格,将显示一个占位符960px x 960px,直到完整的图像加载,在这一点上将是960px x Y(其中Y是正确的高度).

我的问题是如何获得占位符图像来模拟实际图像的最终加载尺寸?

解决方法

您可以使用以下解决方案实现所需的效果.

HTML:

<img src="blank.gif" class="lazy" 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: If you want the placeholder rectangle to be visible and in one color,consider using a 1×1 px image for blank.gif. It will load
very fast and will stretch nicely to your proportions,filling it with
the color of your choosing.

JavaScript的:

/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:  
 * `<img src="blank.gif" 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脚本可以找到here.

猜你在找的HTML相关文章