具有声明的宽度和高度的图像在加载之前呈现正方形 [英] Image with declared width and height renders square before load

查看:80
本文介绍了具有声明的宽度和高度的图像在加载之前呈现正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有具有已声明宽度和高度的图片,例如:

 < img src =foo.jpgwidth = 1500height =1800alt =bar/> 

它们在响应式网格内,因此它们显示在 max-width: 100%。问题是,尽管有 height:auto; ,图片总是显示之前的正方形,这会创建一个跳转



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



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

解决方案

您可以通过以下解决方案实现所需的效果。



HTML



 < img src =blank.gifclass = lazydata-src =foo.pngwidth =1500height =1800alt =bar> 
▲▲
║╚═══该类将用于下面的延迟加载器

╚═══使用有缺陷的gif隐藏它在加载之前显示




提示:如果您需要占位符矩形以一种颜色显示,请考虑为 blank.gif 使用1x1像素的图片。它会加载
非常快,将拉伸到你的比例,填充它
你选择的颜色。


JavaScript

  / * lazyload.js(c)Lorenzo Giuliani 
* MIT许可证(http://www.opensource.org/licenses/mit-license.html)
*
*需要一个列表:
*`< img src =blank .gifdata-src =my_image.pngwidth =600height =400class =lazy>`
* /

!function
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 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(){
(image i [i],function(){
)($ i = 0; i if(elementInViewport(images [i] images.splice(i,i);
});
}
};
}
;
// Array.prototype.slice.call在我们可爱的IE8下不可调用
for(var i = 0; i< query.length; i ++){
images.push [一世]);
};

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

}(this);

资料来源:
可以找到Lazyload脚本此处


I have images with declared widths and heights, e.g.:

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

They are within a responsive grid, so they display at max-width: 100%. They are lazyloaded in. The problem is that despite having height: auto;, the images always display square before they are loaded, which creates a jump in page height when they have finished loading.

So the above image example, in my 960px width grid, would display a placeholder at 960px x 960px until the full image loads, at which point it will be 960px x Y (where Y is the correct height).

My question is how can I get the placeholder image to mimic the final loaded dimensions of the actual image?

解决方案

You can achieve the desired effect with the following solution.

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: If you want the placeholder rectangle to be visible and in one color, consider using a 1x1 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" 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: The Lazyload script can be found here.

这篇关于具有声明的宽度和高度的图像在加载之前呈现正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆