業務需要,從后台獲取的圖片列表,用img標簽展示,用戶需要查看大圖。記錄下來以便學習和參考.示例圖如下:
放大之前:
放大之后:
點擊后放大(由於圖片高度超出了頁面,需要通過overflow:auto;設置滾動條,點擊放大圖片回到列表界面)
附代碼(js實現):
1、獲取所有img標簽,添加展開功能,該方法在圖片列表加載完成以后執行:
1 function addExpand() { 2 var imgs = document.getElementsByTagName("img"); 3 imgs[0].focus(); 4 for(var i = 0;i<imgs.length;i++){ 5 imgs[i].onclick = expandPhoto; 6 imgs[i].onkeydown = expandPhoto; 7 } 8 }
2、方法1種循環給圖片的onclick和onckeydown指定了expandPhoto方法,該方法實現了點擊圖片放大的功能:
1 function expandPhoto(){ 2 var overlay = document.createElement("div"); 3 overlay.setAttribute("id","overlay"); 4 overlay.setAttribute("class","overlay"); 5 document.body.appendChild(overlay); 6 7 var img = document.createElement("img"); 8 img.setAttribute("id","expand") 9 img.setAttribute("class","overlayimg"); 10 img.src = this.getAttribute("src"); 11 document.getElementById("overlay").appendChild(img); 12 13 img.onclick = restore; 14 }
3、(style樣式)方法2中,expndPhoto創建了一個id="overlay",class="overlay"的div,再給div創建了一個id="expand",class="overlayimg"的img標簽,overlay和overlayimg類選擇器定義如下:
<style> .overlay{ background-color:#000; //背景色 opacity: 1.0; //不透明度 filter:alpha(opacity=100); //透明度 position: fixed; top:0; left:0; width:100%; height:100%; z-index: 10; overflow:auto; //滾動條 } .overlayimg{ position: absolute; z-index: 11; width:99%; //寬度 height:auto; //高度自動 } </style>
4、方法2中,給創建的img標簽的onclick指定了restore方法,該方法實現了點擊大圖回到圖片列表的功能,定義如下:
1 function restore(){ 2 document.body.removeChild(document.getElementById("overlay")); 3 document.body.removeChild(document.getElementById("expand")); 4 }
5、復制粘貼即可
原文鏈接:https://blog.csdn.net/weixin_33890526/article/details/94694759