In diesem Artikel zeigen wir Ihnen, wie Sie JavaScript und CSS verwenden, um ein Bild-Popup zu erstellen.

Bildressourcen:

HTML-Code:

<!--Popup auslösen – Ändern Sie das Bild in Ihre Bild-URL--> <img id="myImg" src="img.jpg" alt="Textbeschreibung" width="300" height="200"> <!--Popup--> <div id="myModal" class="modal"> <!--Schließen-Button--> <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span> <!--Popup-Inhalt--> <img class="modal-content" id="img01"> <!--Textbeschreibung--> <div id="caption"></div> </div>

CSS-Code:

/*Styles für das Bild, das das Popup auslöst*/ #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hover {opacity: 0.7;} /*Popup-Hintergrund*/ .modal { display: none; /* Standardmäßig ausgeblendet */ position: fixed; /* Bleibt an Ort und Stelle */ z-index: 1; /* Ganz oben liegen */ padding-top: 100px; /* Position der Box */ left: 0; top: 0; width: 100%; /* Volle Breite */ height: 100%; /* Volle Höhe */ overflow: auto; /* Scrollen bei Bedarf aktivieren */ background-color: rgb(0,0,0); /* Ersatzfarbe */ background-color: rgba(0,0,0,0.9); /* Schwarz mit Deckkraft */ } /*Bild*/ .modal-content { margin: auto; display: block; width: 80%; max-width: 700px; } /*Textinhalt*/ #caption { margin: auto; display: block; width: 80%; max-width: 700px; text-align: center; color: #ccc; padding: 10px 0; height: 150px; } /*Animation hinzufügen*/ .modal-content, #caption { -webkit-animation-name: zoom; -webkit-animation-duration: 0.6s; animation-name: zoom; animation-duration: 0.6s; } @-webkit-keyframes zoom { from {-webkit-transform:scale(0)} to {-webkit-transform:scale(1)} } @keyframes zoom { from {transform:scale(0)} to {transform:scale(1)} } /*Schließen-Schaltfläche*/ .close { position: absolute; top: 15px; right: 35px; color: #f1f1f1; font-size: 40px; font-weight: bold; transition: 0.3s; } .close:hover, .close:focus { color: #bbb; text-decoration: none; cursor: pointer; } /*Auf kleinen Bildschirmen ist die Bildbreite 100%*/ @media only screen and (max-width: 700px){ .modal-content { width: 100%; } }

JavaScript-Code:

//Popup abrufen var modal = document.getElementById('myModal'); //Das Bild abrufen und in das Popup einfügen – verwenden Sie das "alt"-Attribut als Inhalt des Textabschnitts var img = document.getElementById('myImg'); var modalImg = document.getElementById("img01"); var captionText = document.getElementById("caption"); img.onclick = function(){ modal.style.display = "block"; modalImg.src = this.src; captionText.innerHTML = this.alt; } //Das <span>-Element abrufen, um die Schließen-Schaltfläche einzurichten var span = document.getElementsByClassName("close")[0]; //Wenn Sie auf (x) klicken, schließen Sie das Popup span.onclick = function() { modal.style.display = "none"; }

Online-Demo