模态 javascript 代码只能暂时工作?

Modal javascript code only works temporarily?

有人能猜出为什么这个简短的脚本不起作用吗?

奇怪的是,我只让它在 CodePen 上工作,而且只是暂时的(即如果它在你保存然后停止后会在预览中工作一段时间)

https://gist.github.com/IlanVivanco/694a19541ba58590e149df9cdccef4aa

https://codepen.io/alain_invasion/pen/mdmXPgq

BulmaModal.js

class BulmaModal {
   constructor(modalButton) {
     const target = modalButton.dataset.target;

     if (target) {
       this.button = modalButton;
       this.modal = document.querySelector(target);
       this.html = document.querySelector("html");

       this.openEvent();
       this.closeEvents();
     }
   }

   show() {
     this.modal.classList.toggle("is-active");
     this.html.classList.add("is-clipped");

     this.onShow();
   }

   close() {
     this.modal.classList.toggle("is-active");
     this.html.classList.toggle("is-clipped");

     this.onClose();
   }

   openEvent() {
     this.button.addEventListener("click", (e) => {
       e.preventDefault();
       this.show();
     });
   }

   closeEvents() {
     const closeElements = this.modal.querySelectorAll(".modal-background, .modal-close");

     closeElements.forEach((element) => {
       element.addEventListener("click", (e) => {
         e.preventDefault();
         this.close();
       });
     });
   }

   onShow() {
     const event = new Event("modal:show");
     this.modal.dispatchEvent(event);
   }

   onClose() {
     const event = new Event("modal:close");
     this.modal.dispatchEvent(event);
   }
 }

 export default BulmaModal;

index.html

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css">
<button class="modal-button" data-toggle="modal" data-target="#video">Open modal</button>

<div class="modal" id="video">
  <div class="modal-background"></div>
  <div class="modal-content">
    Lorem ipsum dolor sit amet
  </div>
  <button class="modal-close is-large" aria-label="close"></button>
</div>

<script src="./main.js" type="module"></script>

main.js

import BulmaModal from './BulmaModal.js'

const modals = document.querySelectorAll("[data-toggle='modal']");
modals.forEach((modal) => new BulmaModal(modal));

/** show events */
document.querySelector(".modal").addEventListener("modal:show", (event) =>{ console.log(event) });

/** show events */
document.querySelector(".modal").addEventListener("modal:close", (event) =>{ console.log(event) });

如果有人遇到同样的问题:javascript 模块无法在本地 PC 或 CodePen 上运行。因此,如果您发现自己处于同样的情况,解决方案是要么在 Web 服务器上工作(本地或在线),要么编辑脚本以完全避免模块(我就是这样做的)