当前位置: 首页 > Web前端 > JavaScript

图片预览实现方案

时间:2023-03-27 13:29:19 JavaScript

1、添加样式首先在系统中添加弹窗依赖的样式类。定义样式/*图片预览弹出层*/.picmodal{display:none;/*默认隐藏*/position:fixed;/*留在原地*/z-index:1;/*位于顶部*/padding-top:100px;/*盒子的位置*/left:0;顶部:0;宽度:100%;/*全宽*/高度:100%;/*全高*/overflow:auto;/*如果需要启用滚动*/background-color:rgb(0,0,0);/*后备颜色*/background-color:rgba(0,0,0,0.9);/*黑色带不透明度*/}/*图片*/.picmodal-content{margin:auto;显示:块;宽度:80%;max-width:700px;}/*文本内容*/#caption{margin:auto;显示:块;宽度:80%;最大宽度:700px;文本对齐:居中;颜色:#ccc;填充:10px0;height:150px;}/*添加动画*/.picmodal-content,#caption{-webkit-animation-name:zoom;-webkit-动画持续时间:0.6s;动画名称:缩放;animation-duration:0.6s;}@-webkit-keyframeszoom{from{-webkit-transform:scale(0)}to{-webkit-transform:scale(1)}}@keyframeszoom{from{transform:scale(0)}to{transform:scale(1)}}/*关闭按钮*/.picmodal-close{位置:绝对;顶部:15px;右:35px;颜色:#f1f1f1;字体大小:40px;字体粗细:粗体;transition:0.3s;}.picmodal-close:hover,.picmodal-close:focus{颜色:#bbb;文字修饰:无;cursor:pointer;}/*图片在小屏的宽度为100%*/@mediaonlyscreenand(max-width:700px){.picmodal-content{width:100%;}}二、脚本实现可以在全局脚本中定义如下方法,调用picPreview方法传入图片地址functionpicPreview(picUrl){//动态创建预览dom元素varpicModal=document.createElement('div');picModal.setAttribute('id','picModal');picModal.setAttribute('class','picmodal');picModal.innerHTML=`×`;document.body.appendChild(picModal);//显示预览varmodalImg=document.getElementById("picModalImg");modalImg.src=picUrl;picModal.style.display="方块";//关闭预览varspan=document.getElementsByClassName("picmodal-close")[0];span.onclick=function(){picModal.remove();}}像这样调用://使用varpicUrl='https://c.runoob.com/wp-content/uploads/2017/01/btotbhpudiagtmvlkyrs.jpg';picPreview(picUrl)