Wie erstellt man: CSS/JS Modal
Lernen Sie, wie man Modale mit CSS und JavaScript erstellt.
Wie erstellt man ein Modal?
Ein Modal ist ein Dialog-/Pop-up-Fenster, das oben auf der aktuellen Seite angezeigt wird:
Schritt 1 - HTML hinzufügen:
<!-- Auslösen/Öffnen des Modals --> <button id="myBtn">Modal öffnen</button> <!-- Modal --> <div id="myModal" class="modal"> <!-- Modal-Inhalt --> <div class="modal-content"> <span class="close">×</span> <p>Einige Texte im 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"; } }
Fügen Sie Kopf und Fuß hinzu
Fügen Sie Klassen für Kopf und Fuß der Modaldialogbox hinzu:
/* Modal Inhalt --> <div class="modal-content"> <div class="modal-header"> <span class="close">×</span> <h2>Modal Kopf</h2> </div> <div class="modal-body"> <pEinige Texte im Modal Haupttext</p> <p>Einige andere Texte...</p> </div> <div class="modal-footer"> <h3>Modal Fußzeile</h3> </div> </div>
Stellen Sie die Stile für Kopf, Haupttext und Fuß der Modaldialogbox ein und fügen Sie eine Animation hinzu (Modaldialogbox fliegt herein):
/* Kopf der Modaldialogbox */ .modal-header { padding: 2px 16px; background-color: #5cb85c; color: white; } /* Haupttext der Modaldialogbox */ .modal-body {padding: 2px 16px;} /* Fuß der Modaldialogbox */ .modal-footer { padding: 2px 16px; background-color: #5cb85c; color: white; } /* Inhalt der Modaldialogbox */ .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 } /* Animation hinzufügen */ @keyframes animatetop { from {top: -300px; opacity: 0} to {top: 0; opacity: 1} }
Untere Modaldialogbox
Erstellen Sie eine vollständige Breite Modaldialogbox, die von unten hereinfliegt:
Beispiel - Untere Modaldialogbox
相关页面
教程:如何创建模态图像
教程:如何创建灯箱