用promise寫一個對話框

沒有做過多的樣式的修飾。只是對近期研究promise的做出來的。

操作流程: 點擊創建按鈕——>顯示對話框——>關閉和失敗按鈕——>對話框關閉;

點擊創建按鈕——>顯示對話框——>成功按鈕——>做對應的操作——>對話框關閉;

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            padding: 0;margin:0;}
        .dialog{
            position: absolute;
            width:100%;
            height: 100%;left:0;top:0;
            background: rgba(0,0,0,.4);
        }
        button{padding:5px 12px;}
        #closedbutton{
            float: right;font-size:12px;padding:4px 8px;
            color: #000;}
    </style>
</head>
<body>
<button οnclick="crea()">創建</button>
<div class="dialog" id="dialog" style="display: none;">
    <div class="diabody" id="diabody" style="width:350px;height: 100px;position: absolute;left:50%;top:50%;padding:10px; margin-left:-175px;margin-top:-50px; background: #fff;border:1px solid blue;">
        <div class="title">確定要刪除此條數據嗎?<a href="javascript:;" id="closedbutton">關閉</a></div>
        <div style="padding:20px;text-align:center;line-height: 35px;">
            <button id="suc">成功</button>
            <button id="err">失敗</button>
        </div>
    </div>
</div>

<script>
    var src = document.getElementById('suc');
    var err = document.getElementById('err');
    var dia = document.getElementById("dialog");
    var diab = document.getElementById("diabody")
    var closedbutton = document.getElementById("closedbutton")
    console.dir(src);
    function createdPor(attr){
        return new Promise(function(resolve,reject){
            src.addEventListener('click', function () {
                resolve();
            })
            err.addEventListener('click',function () {
                reject();
            })
            closedbutton.addEventListener('click',function () {
                reject();
            })
        });
    }
    function  crea() {
        let pro = createdPor();
        dia.style.display = 'block';
        pro.then(()=>{
            alert('進行你要的操作');
            dia.style.display = 'none';
        }).catch(()=>{
            dia.style.display = 'none';
        })
    }
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章