img{padding:5px;width:100px;height:auto;cursor: pointer;}
.overlay{
background-color:rgba(0, 0, 0, 0.7);
position: fixed;
top:0;
left:0;
width:100%;
height:100%;
z-index: 10;
}
.overlayimg{
position: absolute;
z-index: 11;
left: 50%;
top: 55px;
width: auto;
max-width: 92%;
cursor: pointer;
transform: translate(-50%, 0);
}
function expandPhoto(){
var overlay = document.createElement("div"); //创建div
overlay.setAttribute("id","overlay"); //给div添加id
overlay.setAttribute("class","overlay"); //给div添加class
document.body.appendChild(overlay); //向页面中显示此div
var img = document.createElement("img");
img.setAttribute("class","overlayimg");
img.src = this.getAttribute("src");
document.getElementById("overlay").appendChild(img);
img.onclick = restore;
}
function restore(){
document.body.removeChild(document.getElementById("overlay"));
}
window.onload = function(){
var imgs = document.getElementsByTagName("img");//找到所有img
imgs[0].focus();
for(var i = 0;i<imgs.length;i++){
imgs[i].onclick = expandPhoto; //绑定点击事件,执行方法
imgs[i].onkeydown = expandPhoto;
}
}
网页里的缩略图正常写就可以了,如果页面内容比较多,可以给需要放大的缩略图添加相同的类名