直接上代码(复制可用)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>点击图片试试</title>
<style>
.show-img-bg{
display: flex;
align-items: center;
position:fixed;
top:0;
left:0;
background:rgba(0,0,0,0.7);
z-index:2;
width:100%;
height:100%;
}
.bg-title{
position: absolute;
right: 20px;
color: red;
z-index: 99;
}
.lar-img{
display: block;
margin: 0 auto;
z-index: 3;
width:800px;
height: auto;
cursor: pointer;
border:2px solid #fff;
}
.close-icon{
position: absolute;
top: 0;
right: 0;
color: #000000;
background-color: #fff;
font-size: 20px;
font-weight: bold;
padding: 8px 16px;
border: #fff 1px solid;
}
.download-btn{
position: absolute;
right: 50px;
bottom: 100px;
padding: 8px 24px;
color: #000000;
}
.ori-btn{
position: absolute;
right: 50px;
bottom: 160px;
padding: 8px 24px;
color: #000000;
}
</style>
</head>
<body>
<img src="https://img-blog.csdnimg.cn/20200410144904804.png" style="padding:5px;width:200px;height:auto;cursor: pointer;border: 2px solid red;" title="点击图片放大" onclick="expandPhoto(this);"/>
</body>
<script>
function expandPhoto(obj){
var _this = obj;
var bg = document.createElement("div");
bg.setAttribute("id","showImgBg");
bg.setAttribute("class","show-img-bg");
document.body.appendChild(bg);
const bgId = document.getElementById("showImgBg");
var title = document.createElement("span");
title.setAttribute("class","bg-title");
title.innerHTML = "双击图片可放大缩小,按键部分可用";
bgId.appendChild(title);
var larimg = document.createElement("img");
larimg.setAttribute("id","larImg");
larimg.setAttribute("class","lar-img");
larimg.src = _this.getAttribute("src");
bgId.appendChild(larimg);
var close = document.createElement("span");
close.setAttribute("id","closeIcon");
close.setAttribute("class","close-icon");
close.innerHTML = "x";
bgId.appendChild(close);
var downloadBtn = document.createElement("input");
downloadBtn.setAttribute("type","button");
downloadBtn.setAttribute("class","download-btn");
downloadBtn.setAttribute("id","downloadBtn");
downloadBtn.setAttribute("value","下载");
bgId.appendChild(downloadBtn);
var oriBtn = document.createElement("input");
oriBtn.setAttribute("type","button");
oriBtn.setAttribute("class","ori-btn");
oriBtn.setAttribute("id","oriBtn");
oriBtn.setAttribute("value","还原");
bgId.appendChild(oriBtn);
larimg.onclick = bigImg;
oriBtn.onclick = oriImg;
downloadBtn.onclick = download;
close.onclick = restore;
}
function restore(){
document.body.removeChild(document.getElementById("showImgBg"));
}
function bigImg(){
let lar = document.getElementById("larImg");
if(lar.style.width == '800px'){
lar.style.width = "1200px";
}else{
lar.style.width = "800px";
}
}
function oriImg(){
let lar = document.getElementById("larImg");
lar.style.width = "800px";
}
function download(){
alert("下不了的,别点了");
}
</script>
</html>