JS点击img图片放大再次点击缩小JS实现 简单实用Ctrl+C+V就可以用

业务需要,从后台获取的图片列表,用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;
               100%;
               height:100%;
               z-index: 10;
               overflow:auto; //滚动条
           }
           .overlayimg{
               position: absolute;
               z-index: 11;
               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

原文地址:https://www.cnblogs.com/guozhaoxin/p/11855828.html