首页 > 解决方案 > 制作带有可点击背景的模态,无需 JavaScript

问题描述

我想制作一个不使用 JavaScript 但能够单击背景关闭模态的简单模态。

我找到了我喜欢的这个演示,除了有没有办法让地址栏不包含模式的 id?或者是否有另一个技巧可以在没有 JavaScript 的情况下制作具有可点击背景的模式。

https://www.script-tutorials.com/demos/222/index.html

标签: cssbackgroundmodal-dialog

解决方案


我希望这是你所需要的(下面有一个活生生的例子)。

但我的解决方案有一个限制:只能有一个模态窗口 - 不能再多了!

原意:https ://www.cssscript.com/minimal-overlay-modal-pure-css/

.js-btn:focus ~ #modal, .js-btn:active ~ #modal,
#modal:focus {
  visibility: visible;
  opacity: 1;
}

body {
  font-family: serif;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  transition: opacity 200ms;
  visibility: hidden;
  opacity: 0;
  transition: 500ms;
}
.overlay .cancel {
  position: absolute;
  width: 100%;
  height: 100%;
  cursor: default;
}
.modal {
  margin: 100px auto;
  padding: 20px;
  background: #fff;
  border: 1px solid #666;
  width: 300px;
  border-radius: 6px;
  box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
  position: relative;
}

button {
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  cursor: pointer;
  display: block;
  font-weight: 300;
  height: 50px;
  padding: 15px;
  text-align: center;
  border-radius: 6px;
  margin: 40px auto;
  max-width: 200px;
  opacity: 1;
  color: #333;
  text-decoration: none;
  transition: 0.3s box-shadow ease;
  transform: translateY(0px);
  text-shadow: 0 0 0;
}

button:hover { box-shadow: 0 12px 23px rgba(0, 0, 0, 0.23), 0 10px 10px rgba(0, 0, 0, 0.19); }
<h1 align="center">Puse CSS Modal with overlay</h1>

<button class="js-btn">Open Modal</button>

<div id="modal" class="overlay" tabindex="-1">
  <a class="cancel" href="#"></a>
  <div class="modal">
    <h2>This is Modal Overlay 1</h2>
    <div class="content">
      <p>Click outside the modal to close.</p>
    </div>
  </div>
</div>


推荐阅读