# 图片模糊加载

需要使用到JS中的HTML对象中的Image类

# new Image()基本用法

var img=new Image([宽度],[高度]) 属性:border|complete|height|hspace|lowsrc|name|src|vspace|width 事件:onabort|onerror|onkeydown|onkeypress|onkeyup|onload

参考代码:

var img = new Image();  
img.onload = function () {
  alert("img is loaded")
};  
img.onerror = function () {
  alert("error!")
};  
img.src = "http://www.baidu.com/img.gif";  
function show(){
  alert("body is loaded");
}  
window.onload = show;  

# 具体实现:

<!DOCTYPE html>
<html>
  <head>
    <title>大图片加载从模糊到清晰</title>
    <style type="text/css">
        .content {
            position: relative;
        }
        .thumbnails {
            width: 300px;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
            filter: blur(4px);
            transition: all 0.7s;
        }
        .complete {
            filter: blur(0);
        }
    </style>
</head>

<body>
    <div class="content">
        <img class="thumbnails" src="http://img8.zol.com.cn/bbs/upload/10569/10568721.jpg">
    </div>
    <script type="text/javascript">
      var ele = document.querySelector('.thumbnails');
        // 为了看到效果加个延时
      setTimeout(function () {
        // 若图片URL失效请自行替换
        var imgUrl = 'http://img8.zol.com.cn/bbs/upload/10569/10568721.jpg';
        var imgObject = new Image();
        imgObject.src = imgUrl;//创建一个图片即开始请求图片,
        imgObject.onload = function () {//当图像装载完毕时调用的事件。
          ele.src = imgUrl;
          ele.setAttribute('class', 'thumbnails complete');
        }
      }, 1000)
  </script>
</body>
</html>

Last Updated: 8/1/2021, 1:43:20 PM