1. 程式人生 > >圖片預載入 loading

圖片預載入 loading

loading進度條

var index = 0,
    len = imgs.length,
    count = 0,
    $progress = $('.progress');
$.each(imgs,function(i, src){
    var imgObj = new Image();
    $(imgObj).on('load error', function(){
        $progress.html(Math.round((count + 1) / len * 100)) + '%';
        //全部圖片載入完畢,loading隱藏
        if
(count >= len -1){ $('.loading').hide(); document.title = '1/'+len; } count++ }) imgObj.src = src; })

完整程式碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head
>
<style type="text/css"> html, body { width: 100%; height: 100%;} .loading { width: 100%; height: 100%; position: fixed; left: 0; top: 0; left: 0; bottom: 0;background: #fff;text-align: center;font-size: 30px;} .progress { margin-top: 300px;} .btnbox { text-align: center;} .btnbox .btn { padding: 10px 30px; border
: 1px solid #333
; color: #333; display: inline-block;}
</style> <body> <div class="imgWrapper"> <img src="http://pic1.ulecdn.com/item/user_0102/desc20180702/22110364ec48d0bc_-1x-1.jpg" alt="" id="img"> <p class="btnbox"><a href="javascript:;" class="btn" data-prop="prev">上一頁</a> <a href="javascript:;" class="btn" data-prop="next">下一頁</a></p> </div> <div class="loading"> <p class="progress"> 0%</p> </div> </body> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script type="text/javascript"> $(function() { var imgs = ['http://pic1.ulecdn.com/item/user_0102/desc20180702/22110364ec48d0bc_-1x-1.jpg', 'http://pic0.ulecdn.com/item/user_0102/desc20180629/c4a430f1548aba53_-1x-1.jpg', 'http://pic1.ulecdn.com/item/user_0102/desc20180704/ddb4a1e9597575cc_-1x-1.jpg', 'http://pic4.ulecdn.com/item/user_0102/desc20180627/0b65a542456aa6af_-1x-1.jpg']; var index = 0, len = imgs.length, count = 0, $progress = $('.progress'); $.each(imgs, function(i, src) { var imgObj = new Image(); $(imgObj).on('load error', function() { $progress.html(Math.round((count + 1) / len * 100) + '%'); //全部圖片載入完畢,loading隱藏 if (count >= len - 1) { $('.loading').hide(); document.title = '1/' + len; } count++ }) imgObj.src = src; }) $('.btn').click(function() { if ($(this).data('prop') === 'prev') { index = Math.max(0, --index) } else { index = Math.min(len - 1, ++index) } $('#img').attr('src', imgs[index]) }) }) </script> </html>