如何创建:CSS/JS 模态框
学习如何使用 CSS 和 JavaScript 创建模态框。
如何创建模态框
模态框是一种对话框/弹出窗口,它显示在当前页面的顶部:
第一步 - 添加 HTML:
<!-- 触发/打开模态框 --> <button id="myBtn">Open Modal</button> <!-- 模态框 --> <div id="myModal" class="modal"> <!-- 模态框内容 --> <div class="modal-content"> <span class="close">×</span> <p>Some text in the Modal..</p> </div> </div>
第二步 - 添加 CSS:
/* ກອງສະແດງ (ກາງ) */ .modal { display: none; /* ບໍ່ສະແດງໂດຍກົດໝາຍ */ position: fixed; /* ຢູ່ຂັ້ນທີ່ຫົວຫຼັງ */ z-index: 1; /* ຢູ່ທີ່ຕົ້ນ */ left: 0; top: 0; width: 100%; /* ກວ້າງທັງໝົດ */ height: 100%; /* ສູງທັງໝົດ */ overflow: auto; /* ຖ້າຈະມີການຫຼຸດລົງຈະເປີດການຫຼຸດ */ background-color: rgb(0,0,0); /* ສີດຳຜິວຄັດເບິ່ງ */ background-color: rgba(0,0,0,0.4); /* ສີດຳຜິວບໍ່ຈະແຈ້ງ */ } /* ສະພາບຂອງກອງສະແດງ/ກອງ */ .modal-content { background-color: #fefefe; margin: 15% auto; /* ຫ່າງເທິງສະໜາມ 15%, ແລະຢູ່ກາງ */ padding: 20px; border: 1px solid #888; width: 80%; /* ອາດຈະແຕກຕັ້ງຂອງສະໜາມຈໍ */ } /* ຕັນປິດ */ .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } .close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }
ບາງສິ່ງທີສາມ - ສະເໜີ JavaScript:
// ຊອກຫາກອງສະແດງ var modal = document.getElementById("myModal"); // ຊອກຫາຕັນຈະເປີດກອງສະແດງ var btn = document.getElementById("myBtn"); // ຊອກຫາບັນດາ <span> ທີ່ປິດກອງສະແດງ var span = document.getElementsByClassName("close")[0]; // ບໍ່ມີຄົນຊົງຕັນຈະເປີດກອງສະແດງ btn.onclick = function() { modal.style.display = "block"; } // ບໍ່ມີຄົນຊົງ <span> (x) ຈະປິດກັນກອງສະແດງ span.onclick = function() { modal.style.display = "none"; } // ບໍ່ມີຄົນຊົງຄວາມທີ່ຢູ່ພາຍນອກຂອງກອງສະແດງຕັນເບື້ອງນັ້ນຈະປິດກັນ window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }
ເພີ່ມຫົວຂໍ້ ແລະ ສາບຫຼັງ
ກຳນົດຊະນິດໃຫ້ຫົວຂໍ້, ຕົວມື ແລະ ສາບຫຼັງຂອງກອບທີ່:
<!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <span class="close">×</span> <h2>Modal Header</h2> </div> <div class="modal-body"> <p>Some text in the Modal Body</p> <p>Some other text...</p> </div> <div class="modal-footer"> <h3>Modal Footer</h3> </div> </div>
ການຈັດວິທະຍາສາການຂອງຫົວຂໍ້, ຕົວມື ແລະ ສາບຫຼັງ, ແລະ ກຳນົດການສະແດງ (ກອບທີ່ຫລຸດລົງ):
/* ການສະແດງໃນຫົວຂໍ້ */ .modal-header { padding: 2px 16px; background-color: #5cb85c; color: white; } /* ການສະແດງໃນຕົວມື */ .modal-body {padding: 2px 16px;} /* ການສະແດງໃນສາບຫຼັງ */ .modal-footer { padding: 2px 16px; background-color: #5cb85c; color: white; } /* ການສະແດງໃນກອບທີ່ */ .modal-content { position: relative; background-color: #fefefe; margin: auto; padding: 0; border: 1px solid #888; width: 80%; box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19); animation-name: animatetop; animation-duration: 0.4s } /* ກຳນົດການສະແດງ */ @keyframes animatetop { from {top: -300px; opacity: 0} to {top: 0; opacity: 1} }
ກອບທີ່ຢູ່ດ້ານລຸ່ມ
ສ້າງກອບທີ່ສາມາດຫລຸດລົງຈາກດ້ານລຸ່ມທີ່ມີແນວໄປທົ່ວຄວາມກວ້າງ
ຕົວຢ່າງ - ກອບທີ່ຢູ່ດ້ານລຸ່ມ
相关页面
教程:如何创建模态图像
教程:如何创建灯箱