js implementation of img click to enlarge

For business needs, get a list of pictures from the background and display them with the img tag. Since the picture is too small to see clearly, you need to click to enlarge, similar to the following effect:

Click to enlarge (click to enlarge the picture to return to the list interface):

js implementation:
1. Get all img tags and add the expansion function. This method is executed after the image list is loaded:

            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. Method 1 A loop specifies the expandPhoto method for onclick and onckeydown of the picture, which realizes the function of clicking on the picture to enlarge:

            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. In method 2, expndPhoto creates a div with id="overlay" and class="overlay", and then creates an img tag with id="expand" and class="overlayimg" for the div, and selects the overlay and overlayimg classes The device is defined as follows:

           .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. In method 2, the restore method is specified for the onclick of the created img tag. This method realizes the function of clicking the large image to return to the image list, which is defined as follows:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326147616&siteId=291194637