img点击放大的js实现

业务需要,从后台获取图片列表,用img标签展示,由于图片太小看不清,需要点击放大,类似如下效果:

点击后放大(点击放大图片回到列表界面):

js实现:
1、获取所有img标签,添加展开功能,该方法在图片列表加载完成以后执行:

            function addExpand() {
                var imgs = document.getElementsByTagName("img");
                imgs[0].focus();
                for(var i = 0;i<imgs.length;i++){
                    imgs[i].onclick = expandPhoto;
                    imgs[i].onkeydown = expandPhoto;
                }
            }

2、方法1种循环给图片的onclick和onckeydown指定了expandPhoto方法,该方法实现了点击图片放大的功能:

            function expandPhoto(){
                var overlay = document.createElement("div");
                overlay.setAttribute("id","overlay");
                overlay.setAttribute("class","overlay");
                document.body.appendChild(overlay);

                var img = document.createElement("img");
                img.setAttribute("id","expand")
                img.setAttribute("class","overlayimg");
                img.src = this.getAttribute("src");
                document.getElementById("overlay").appendChild(img);

                img.onclick = restore;
            }

3、方法2中,expndPhoto创建了一个id="overlay",class="overlay"的div,再给div创建了一个id="expand",class="overlayimg"的img标签,overlay和overlayimg类选择器定义如下:

           .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; //高度自动
           }

4、方法2中,给创建的img标签的onclick指定了restore方法,该方法实现了点击大图回到图片列表的功能,定义如下:

            function restore(){
                document.body.removeChild(document.getElementById("overlay"));
                document.body.removeChild(document.getElementById("expand"));
            }

猜你喜欢

转载自www.cnblogs.com/kibana/p/9014203.html
今日推荐