首页 > 解决方案 > 如何在没有 jQuery 或 bootstrap.js javascript 的情况下打开 Bootstrap 模式?

问题描述

我正在开发一个非常轻量级的调查应用程序。此应用程序在连接非常有限的第三世界国家/地区运行。

我们发现加载时间与用户参与度成正比(对我们来说非常重要)。

今天我使用了 2 个库——VueJS 和一个自定义引导程序构建。我想调用一个模态。但是模态需要添加 Bootstrap Javascript 和 jQuery。这些库几乎使加载时间加倍。

如何在不添加这两个库的情况下打开模式?

标签: javascriptbootstrap-4

解决方案


@uday 到 CSS only modal 的链接是一个不错的技巧,但如果您将#tag 用于其他目的(例如,路由和参数传递),使用起来可能会很尴尬。

所以这里有一个例子,它使用很少的 JS 来实现非常相似的东西。我试图让 Snippet 尽可能小,以便很容易看到正在发生的事情。

var modal = document.querySelector(".modal");
var container = modal.querySelector(".container");

document.querySelector("button").addEventListener("click", function (e) {
  modal.classList.remove("hidden")
});

document.querySelector(".modal").addEventListener("click", function (e) {
  if (e.target !== modal && e.target !== container) return;     
  modal.classList.add("hidden");
});
.modal {
  background-color: rgba(0,0,0,0.4); /* Transparent dimmed overlay */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: table;
}

.modal.hidden {
  display: none;
}

.modal .container {
 display: table-cell;
 text-align: center;
 vertical-align: middle;
 width: 200px;
}

.modal .body {
  box-shadow: 5px 10px #888888;
  display: inline-block;
  background-color: white;
  border: 1px solid black; 
  padding: 10px;
}
<button>Show Modal</button>

<div class="modal hidden">
  <div class="container">
    <div class="body">
      <p>Click outside this box to close the modal.<p>
      <p>You could of course add a close button etc</p>
      <p>But this is left for the OP todo</p> 
    </div>
  </div>
</div>


推荐阅读