js动态点击放大缩小图片

html

<imgclass="img img-toggle"src="xxx.jpg"alt="">

CSS

<style>

    .overlay {

    /*背景色,透明度*/

        background-color: rgba(24 23 23 / 0.85);

        position: fixed;

        top: 0;

        left: 0;

        width: 100%;

        height: 100%;

        z-index: 100;

        /*由于图片高度可能超出了页面,需要设置滚动条*/

        overflow: auto;

        display: flex;

        justify-content: center;

        align-items: center;

        flex-direction: row;

    }

    .overlayimg {

        width: 40%;

        /*宽度*/

        height: auto;

        /*高度自动*/

    }

    /* 鼠标移动到图片变为放大镜 */

    .img-toggle {

        cursor: -webkit-zoom-in;

        cursor: zoom-in;

    }


    .img{

        float: left;

        width: 100px;

        height: 100px !important;

        padding: 10px;

        object-fit: cover;

        border-radius: 20px;

    }

</style>

JS

//该方法在图片列表加载完成以后执行:

window.onload = function () {

addExpand();

}

/*循环给class='img-toggle'图片的onclick和onckeydown指定了expandPhoto方法,

该方法实现了点击图片放大的功能:*/

function addExpand() {

var imgs = document.getElementsByClassName("img-toggle");

imgs[0].focus();

for (var i = 0; i < imgs.length; i++) {

imgs[i].onclick = expandPhoto;

imgs[i].onkeydown = expandPhoto;

}

}

/*expndPhoto创建了一个id="overlay",class="overlay"的div,

再给div创建了一个id="expand",class="overlayimg"的img标签,

overlay和overlayimg类选择器定义如下:*/

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;

}

/*给创建的img标签的onclick指定了restore方法,该方法实现了点击大图回到图片列表的功能*/

function restore() {

document.body.removeChild(document.getElementById("overlay"));

document.body.removeChild(document.getElementById("expand"));

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容