手机国产精品一区二区,另类第一页,亚欧在线,日韩一国产极品99热在线播放69_国产美女久久精品香蕉欧美_亚州中文无码aⅤ在线_免费国产v片在线

簡單有效的JavaScript圖片預(yù)加載效果

2019-12-11    seo達(dá)人

首先編寫一個(gè)簡單的容器:



<style>

content {

    width: 600px;

    height: 100vh;

    overflow-y: auto;

}

 

content ul {

    width: 100%;

}

 

content ul li {

    width: 50%;

    float: left;

    margin: 20px 0;

    list-style: none;

}

 

content ul li p {

    width: 200px;

    height: 200px;

    overflow: hidden;

    margin: 0 auto;

    border: 1px solid #999999;

}

 

content ul li p img {

    width: 100%;

    display: block;

    position: relative;

    top: 50%;

    transform: translateY(-50%);

}

</style>

<div id="content">

   <ul>

   </ul>

</div>

然后,編寫js代碼:



let imageArr = [{

    img_url: "http://www.lexilisi.com/Uploadpth/c45cc952-dcb7-493c-a171-357d1b820b37.png",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_3.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_4.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_5.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_6.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_799.jpg",

}];

const lazyLoad = (src) => {

    //加載loading動(dòng)畫

    let _image = new Image();

    _image.src = './loading.gif';

    //加載需要展示的圖片

    let image = new Image();

    image.src = src;

    //加載成功,將loading圖片路徑改成對應(yīng)的真實(shí)路徑

    image.onload = _ => image.src = .currentTarget.src;

    //加載失敗,將loading圖片路徑改成默認(rèn)圖片路徑

    image.onerror = _ => _image.src = './error.png';

    return _image;

}

let _content = document.getElementById('content');

let _ul = _content.getElementsByTagName('ul');

imageArr.forEach(value => {

    let _li = document.createElement('li');

    let _p = document.createElement('p');

    let _image = lazyLoad(value.img_url);

    _p.appendChild(_image);

    _li.appendChild(_p);

    _ul[0].appendChild(_li);

})

展示效果如圖:







每個(gè)圖片都是異步加載,加載完成后:







 






分享本文至:

日歷

鏈接

個(gè)人資料

存檔