意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

图片预览实现方案

来源:恒创科技 编辑:恒创科技编辑部
2024-01-27 15:11:59
一、添加样式

首先在系统中加入弹窗所依赖的样式类。

定义样式

/* 图片预览弹出层 */
.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 = '/news/upload/ueditor/image/202209/zakas3nchio.jpg
picPreview(picUrl)
上一篇: 前端面试题JavaScript篇——2022-09-15 下一篇: 手机怎么远程登录云服务器?