首页html-css

如何用 HTML css 和 JavaScript 写一个模态框(modal)

hfpp2012发布于900 次阅读

先看下效果:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Simple Modal</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <button id="modalBtn" class="button">Click Here</button>

  <div id="simpleModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="closeBtn">&times;</span>
        <h2>Modal Header</h2>
      </div>
      <div class="modal-body">
        <p>Hello...I am a modal</p>
        <p>Lorem ipsum dolor sit amet, consectetur magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
        ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
        velit esse cillum dolore eu fugiat nulla pariatur.  Excepteur sint occaecat cupidatat non proident, sunt in
        culpa qui officia deserunt mollit anim id est laborum</p>
      </div>
      <div class="modal-footer">
        <h3>Modal Footer</h3>
      </div>
    </div>
  </div>

  <script src="main.js"></script>
</body>
</html>

main.js

var modal = document.getElementById('simpleModal');

var modalBtn = document.getElementById('modalBtn');

var closeBtn = document.getElementsByClassName('closeBtn')[0];

modalBtn.addEventListener('click', openModal);

closeBtn.addEventListener('click', closeModal);

window.addEventListener('click', outsideClick);

function openModal() {
  modal.style.display = "block";
}

function closeModal() {
  modal.style.display = 'none';
}

function outsideClick(e) {
  if (e.target == modal) {
    modal.style.display = 'none';
  }
}

style.css

body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 17px;
  line-height: 1.6;
}

.button {
  background: coral;
  padding: 1em 2em;
  color: #fff;
  border: 0;
}

.button:hover {
  background: #333;
}

.button:focus {
  outline: none;
}

.modal {
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #f4f4f4;
  margin: 20% auto;
  width: 70%;
  box-shadow: 0 5p 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
  animation-name: modalopen;
  animation-duration: 3s;
}

.modal-header {
  background: coral;
  padding: 15px;
  color: #fff;
}

.modal-body {
  padding: 10px 20px;
}

.modal-footer {
  background: coral;
  padding: 10px;
  color: #fff;
  text-align: center;
}

.closeBtn {
  color: #ccc;
  float: right;
  font-size: 30px;
  color: #fff;
}

.closeBtn:hover, .closeBtn:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

@keyframes modalopen {
  from { opacity: 0 }
  to { opacity: 1 }
}

完结。

本站文章均为原创内容,如需转载请注明出处,谢谢。

0 条回复
暂无回复~~
喜欢
友情提示

© Rails365 | 隐私条款 | 服务条款 | 粤ICP备15004902号

Top