【问题标题】:modal popup on pageload in web componentWeb 组件中页面加载时的模式弹出窗口
【发布时间】:2025-12-08 07:05:01
【问题描述】:

我是 lit-element 的新手,我想使用 litelement 创建一个模态组件,模态应该在页面加载时显示并在 20 秒后自动关闭。
这是我的代码 sn-p:

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);

【问题讨论】:

    标签: javascript web components bootstrap-modal lit-element


    【解决方案1】:

    您可以简单地添加此 JavaScript 代码,

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

    【讨论】:

    • 感谢及时回复,但是如何使用litelement实现,
    【解决方案2】:

    尝试将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);
    }
    

    【讨论】:

      最近更新 更多