乐趣区

关于javascript:图片预览实现方案

一、增加款式

首先在零碎中退出弹窗所依赖的款式类。

定义款式

/* 图片预览弹出层 */
.picmodal {
    display: none;
    /* Hidden by default */
    position: fixed;
    /* Stay in place */
    z-index: 1;
    /* Sit on top */
    padding-top: 100px;
    /* Location of the box */
    left: 0;
    top: 0;
    width: 100%;
    /* Full width */
    height: 100%;
    /* Full height */
    overflow: auto;
    /* Enable scroll if needed */
    background-color: rgb(0, 0, 0);
    /* Fallback color */
    background-color: rgba(0, 0, 0, 0.9);
    /* Black w/ opacity */
}

/* 图片 */
.picmodal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* 文本内容 */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* 增加动画 */
.picmodal-content,
#caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform: scale(0)
    }
    to {-webkit-transform: scale(1)
    }
}

@keyframes zoom {
    from {transform: scale(0)
    }
    to {transform: scale(1)
    }
}

/* 敞开按钮 */
.picmodal-close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.picmodal-close:hover,
.picmodal-close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 小屏幕中图片宽度为 100% */
@media only screen and (max-width: 700px) {
    .picmodal-content {width: 100%;}
}

二、脚本实现

能够将以下办法定义到全局脚本中,调用 picPreview 办法传入图片地址即可。

function picPreview(picUrl) {
    // 动态创建预览 dom 元素
    var picModal = document.createElement('div');
    picModal.setAttribute('id', 'picModal');
    picModal.setAttribute('class', 'picmodal');
    picModal.innerHTML = `
        <span class="picmodal-close">&times;</span>
        <img id="picModalImg" class="picmodal-content">`;
    document.body.appendChild(picModal);

    // 显示预览
    var modalImg = document.getElementById("picModalImg");
    modalImg.src = picUrl;
    picModal.style.display = "block";

    // 敞开预览
    var span = document.getElementsByClassName("picmodal-close")[0];
    span.onclick = function () {picModal.remove();
    }
}

调用如下:

// 应用
var picUrl = 'https://c.runoob.com/wp-content/uploads/2017/01/btotbhpudiagtmvlkyrs.jpg';
picPreview(picUrl)
退出移动版