HTML代碼:
1 <img id="img0" src="" style="padding-right:10px; " /> 2 3 <div id="myModal" class="modal"> 4 <!-- 關閉按鈕 --> 5 <span class="close"onclick="document.getElementById('myModal').style.display='none'">×</span> 6 <!-- 彈窗內容 --> 7 <img class="modal-content" id="img_content"> 8 </div>
CSS布局:imgbig.css
1 /** 2 *autor:zouyh 2018/10/25 3 */ 4 5 /* 觸發彈窗圖片的樣式 */ 6 #myImg { 7 border-radius: 5px; 8 cursor: pointer; 9 transition: 0.3s; 10 } 11 12 #myImg:hover {opacity: 0.7;} 13 14 /* 彈窗背景 */ 15 .modal { 16 display: none; /* Hidden by default */ 17 position: fixed; /* Stay in place */ 18 z-index: 1; /* Sit on top */ 19 padding-top: 100px; /* Location of the box */ 20 left: 281px; 21 top: 0; 22 width: 100%; /* Full width */ 23 height: 100%; /* Full height */ 24 overflow: auto; /* Enable scroll if needed */ 25 background-color: rgb(0,0,0); /* Fallback color */ 26 background-color: rgba(0,0,0,0.9); /* Black w/ opacity */ 27 } 28 29 /* 圖片 */ 30 .modal-content { 31 margin: auto; 32 display: block; 33 width: 45%; 34 max-width: 45%; 35 height: 90%; 36 } 37 38 39 /* 添加動畫 */ 40 .modal-content, #caption { 41 -webkit-animation-name: zoom; 42 -webkit-animation-duration: 0.6s; 43 animation-name: zoom; 44 animation-duration: 0.6s; 45 } 46 47 @-webkit-keyframes zoom { 48 from {-webkit-transform:scale(0)} 49 to {-webkit-transform:scale(1)} 50 } 51 52 @keyframes zoom { 53 from {transform:scale(0)} 54 to {transform:scale(1)} 55 } 56 57 /* 關閉按鈕 */ 58 .close { 59 position: absolute; 60 top: 15px; 61 right: 35px; 62 color: #f1f1f1; 63 font-size: 40px; 64 font-weight: bold; 65 transition: 0.3s; 66 } 67 68 .close:hover, 69 .close:focus { 70 color: #bbb; 71 text-decoration: none; 72 cursor: pointer; 73 } 74 75 /* 小屏幕中圖片寬度為 100% */ 76 @media only screen and (max-width: 600px){ 77 .modal-content { 78 width: 100%; 79 } 80 }
js實現:
1 $("#img0").click(function(){ 2 // 獲取彈窗 3 var modal = document.getElementById('myModal'); 4 modal.style.display = "block"; 5 // 獲取圖片插入到彈窗 6 var modalImg = document.getElementById("img_content"); 7 modalImg.src = zpadress; 8 // 獲取 <span> 元素,設置關閉按鈕 9 var span = document.getElementsByClassName("close")[0]; 10 // 當點擊 (x), 關閉彈窗 11 span.onclick = function() { 12 modal.style.display = "none"; 13 }; 14 });