简体   繁体   English

使用纯JavaScript在Pageload上出现模式弹出窗口

[英]modal popup on pageload with pure javascript

I would like to know how to create a modal popup without using jquery or boostrap but using javscript. 我想知道如何在不使用jquery或boostrap但使用javscript的情况下创建模态弹出窗口。 Modal popup should show only on page load for 30 sec and close automatically. 模态弹出窗口应仅在页面加载时显示30秒并自动关闭。 have tried using jquery and bootstrap but need to create in javascript 尝试过使用jquery和bootstrap,但需要在javascript中创建

<script>
     $(document).ready(function () {
     $('.modal').modal('show');
      });
  </script>

 <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times; 
            </button>
            <h4 class="modal-title">Load Bootstrap modal on page launch</h4>
          </div>
        <div class="modal-body">
          <p>
           This is a simple Demo to launch a model on page load.
          </p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data- 
           dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

Firstly, whenever you perform any ui operations (such as Opening a modal, accessing dom nodes, etc etc), always wait for the document to be loaded. 首先,每当您执行任何ui操作(例如打开模式,访问dom节点等)时,请始终等待文档被加载。 (The example is in Jquery but you can use vanilla js too). (示例在Jquery中,但是您也可以使用普通js)。

$(document).ready(function () {
 // Perform your operations here
});

Once you show the modal, you could setup a timeOut function setTimeout(hideModal, 500) where 显示模态后,您可以设置一个timeOut函数setTimeout(hideModal, 500) ,其中

hideModal - The function which hides your modal hideModal隐藏模态的函数

500 - Timeout period after which you want to execute the function in ms 500 - 您希望以ms为单位执行该功能的超时时间

Create dom elements for modal and its background. 为模式及其背景创建dom元素。 Initially add a class show then use setTimeout to remove the class from classList after 3 secs 最初添加一个类show然后在3秒钟后使用setTimeout从classList中删除该类

 setTimeout(() => { document.getElementsByClassName('modalContainer')[0].classList.remove('show'); }, 3000) 
 .mainContainer, .modalContainer { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center } .modalContainer { background: black; opacity: 0.5; z-index: 10; display: none; } .modal { width: 200px; height: 200px; z-index: 15; background: red; } .show { display: flex; } body, html { height: 100%; width: 100%; } 
 <div class='mainContainer'> <div class='modalContainer show'> <div class='modal'>Here is the modal</div> </div> </div> 

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

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