jquery defered的progress方法實現進度條

看風景就發表於2018-01-09

效果如圖:

實現程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body{
            padding:30px;
            background-color: lightblue;
        }
        .progressbar{
            height: 10px;
            width: 300px;
            background-color:#fff;
        }
        .progressnum{
            font-size:40px;
            color:#fff;
            text-align: center;
            width: 300px;
            margin:0 auto;
            margin-bottom:40px;
        }
    </style>
</head>
<body>
    <div class="progressnum"></div>
    <div class="progressbar"></div>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(function(){
            var bar = function(){  
                var $d = $.Deferred();
                setTimeout(function(){
                    $d.resolve();
                },3000);
                return $d;
            }

            polling(bar());
        });

        function polling(d){
            var bar = $('.progressbar')[0],
                $num = $('.progressnum');
                d.progress(function(n){
                    console.log(n);
                    $num.html(Math.floor(n/3) + '%');
                    bar.style.width = n + 'px';              
                });

            var n = 10,
                count = 0;
            var timer = setInterval(function(){
                console.log('nodify: ' + n);
                if(d.state() != 'pending'){
                    clearInterval(timer);
                }
                n += 10;
                d.notify(n);
            },100);
        }
    </script>
</body>
</html>

 

相關文章