功能描述
很多网站都是使用浏览器自带图片浏览功能,但看起来很low,想手动实现图片预览功能,点击图片弹出大图预览框在屏幕中间显示,根据图片宽高自适应屏幕大小
效果图
具体代码实现
页面preview.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>preview</title>
<link rel="stylesheet" href="../css/preview.css">
</head>
<body>
<div>
<a href="javascript:;" onclick="showPreviewImg('../images/t1.jpg')">
<img src="../images/t1.jpg" alt="" width="100px" height="100px">
</a>
<a href="javascript:;" onclick="showPreviewImg('../images/t2.jpg')">
<img src="../images/t2.jpg" alt="" width="100px" height="100px">
</a>
<a href="javascript:;" onclick="showPreviewImg('../images/t3.jpg')">
<img src="../images/t3.jpg" alt="" width="100px" height="100px">
</a>
</div>
<div class="preview-img">
<div class="container">
<img src="../images/preview_default.png" alt="">
<a class="close" href="javascript:void(0);"></a>
</div>
</div>
<script src="../js/preview.js"></script>
</body>
</html>
样式preview.css
.preview-img {
display: none;
text-align: center;
width: 100%;
height: 100%;
position: fixed;
left: 0;
top: 0;
z-index: 100;
background: url("../images/fancybox_overlay.png");
}
.preview-img .container {
max-width: 90%;
position: absolute;
padding: 15px;
background-color: #f9f9f9;
border-radius: 5px;
}
.preview-img .container img {
max-width: 100%;
background-size: contain/cover;
}
.preview-img .container a {
display: inline-block;
width: 36px;
height: 36px;
text-decoration: none;
position: absolute;
right: -18px;
top: -18px;
background: url("../images/fancybox_sprite.png") no-repeat;
}
preview.js
var mBody = document.querySelector("body");
var previewImg = document.querySelector(".preview-img");
var mContainer = document.querySelector(".preview-img .container");
var mImg = document.querySelector(".preview-img .container img");
var mClose = document.querySelector(".preview-img .container .close");
function showPreviewImg(url) {
mImg.setAttribute("src", url);
previewImg.style.display = "flex";
previewImg.style.justifyContent = "center";
previewImg.style.alignItems = "center";
setPreviewImgWH();
mBody.style.overflow = "hidden"
}
function setPreviewImgWH() {
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
if (windowWidth < windowHeight) {
mImg.style.width = windowWidth * 0.8 + "px";
mImg.style.height = "auto";
} else {
mImg.style.height = windowHeight * 0.8 + "px";
mImg.style.width = "auto";
}
}
mClose.onclick = function () {
closePreviewImg();
}
mContainer.onclick = function (event) {
event.stopPropagation();
}
previewImg.onclick = function (event) {
closePreviewImg();
}
function closePreviewImg() {
previewImg.style.display = "none";
mBody.style.overflow = "scroll"
}
window.onresize = function () {
if (previewImg.style.display != "none") {
setPreviewImgWH();
}
};
具体实现细节代码已注释,想要使用的只需修改一下图片地址即可,注意css和js的路径地址 我的目录结构
|