Custom “confirm” dialog in JavaScript?

前端 未结 7 1049
悲&欢浪女
悲&欢浪女 2020-12-01 06:33

I\'ve been working on an ASP.net project that uses custom \'modal dialogs\'. I use scare quotes here because I understand that the \'modal dialog\' is simply a div in my ht

7条回答
  •  爱一瞬间的悲伤
    2020-12-01 06:56

    To enable you to use the confirm box like the normal confirm dialog, I would use Promises which will enable you to await on the result of the outcome and then act on this, rather than having to use callbacks.

    This will allow you to follow the same pattern you have in other parts of your code with code such as...

      const confirm = await ui.confirm('Are you sure you want to do this?');
    
      if(confirm){
        alert('yes clicked');
      } else{
        alert('no clicked');
      }
    

    See codepen for example, or run the snippet below.

    https://codepen.io/larnott/pen/rNNQoNp

    const ui = {
      confirm: async (message) => createConfirm(message)
    }
    
    const createConfirm = (message) => {
      return new Promise((complete, failed)=>{
        $('#confirmMessage').text(message)
    
        $('#confirmYes').off('click');
        $('#confirmNo').off('click');
        
        $('#confirmYes').on('click', ()=> { $('.confirm').hide(); complete(true); });
        $('#confirmNo').on('click', ()=> { $('.confirm').hide(); complete(false); });
        
        $('.confirm').show();
      });
    }
                         
    const saveForm = async () => {
      const confirm = await ui.confirm('Are you sure you want to do this?');
      
      if(confirm){
        alert('yes clicked');
      } else{
        alert('no clicked');
      }
    }
    body {
      margin: 0px;
      font-family: "Arial";
    }
    
    .example {
      padding: 20px;
    }
    
    input[type=button] {
      padding: 5px 10px;
      margin: 10px 5px;
      border-radius: 5px;
      cursor: pointer;
      background: #ffffd;
      border: 1px solid #ccc;
    }
    input[type=button]:hover {
      background: #ccc;
    }
    
    .confirm {
      display: none;
    }
    .confirm > div:first-of-type {
      position: fixed;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      top: 0px;
      left: 0px;
    }
    .confirm > div:last-of-type {
      padding: 10px 20px;
      background: white;
      position: absolute;
      width: auto;
      height: auto;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      border-radius: 5px;
      border: 1px solid #333;
    }
    .confirm > div:last-of-type div:first-of-type {
      min-width: 150px;
      padding: 10px;
    }
    .confirm > div:last-of-type div:last-of-type {
      text-align: right;
    }
    
    
    

提交回复
热议问题