简体   繁体   English

Web组件中页面加载的模式弹出窗口

[英]modal popup on pageload in web component

I am newbie to lit-element and I would like to create a modal component using litelement, Modal should show on page load and automatically close after 20 seconds. 我是lit-element的新手,我想使用litelement创建模式组件,Modal应该在页面加载时显示,并在20秒后自动关闭。
Here is my code snippet: 这是我的代码段:

import { LitElement, html } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';

export class Modal extends LitElement {

  connectedCallback(){
    super.connectedCallback();
    this.modalTimer();
  }

  modalTimer(){       
    this.shadowRoot.getElementById("modalContainer").classList.remove('show');
  }

  render() {
    return html`
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">  
      <style>
        .modalContainer {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: black;
          opacity: 0.5;
          z-index: 10;
          display: none;
        }    
        .modal {
          width: 200px;
          height: 200px;
          z-index: 15;
          background: red;
        }
        .show {
          display: flex;
        }
      </style>
      <div id='modalContainer' class="show">
        <div class='modal'>Here is the modal</div>
      </div>    
    `;
  }
}

customElements.define('element-modal', Modal);

You can simply add this JavaScript code, 您只需添加此JavaScript代码,

window.onload = () => {
setTimeout(() => {
$('#modalContainer').modal({show:true});
}, 20000);
}

Try to put fadeOut behavior into firstUpdated() callback function. 尝试将fadeOut行为放入firstUpdated()回调函数中。

firstUpdated (){
  const s = this.shadowRoot.getElementById('modalContainer').style;
  const delayInMilliseconds = 20000; //20 seconds

  // Your code to be executed after 20 seconds
  setTimeout(function() {
    s.opacity = 1;
    // Fade an element out and then remove it
    (function fade() {
      (s.opacity -= 0.1) < 0 ? (s.display = 'none') : setTimeout(fade, 40);
    })();
  }, delayInMilliseconds);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM