在CSDN参考的一篇文章,但是那篇文章失效了(所以没有贴链接)。
原代码无法正确展示图片,是存在问题的,个人对原代码有调整修改。
图片放大思路如下:
1、加载页面时,为图片添加点击事件;
2、点击图片,执行expandPhoto()方法,该方法在页面添加div,用于展示放大后的图片;
3、点击大图,执行retore()方法,该方法用于移除展示大图的div。具体代码如下:
<!DOCTYPE html>
<html lang="gbk">
<head>
<meta charset="gbk">
</head>
<style>
img {
cursor: -webkit-zoom-in;
cursor: zoom-in;
}
img:hover:not(.active) {
opacity: .8;
}
img.active {
cursor: -webkit-zoom-out;
cursor: zoom-out;
}
.overlay{
background-color:#000;
opacity: 1;
position: fixed;
top:10%;
left:10%;
width:90%;
height:90%;
z-index: 10;
text-align: center;
}
.overlayimg{
position: absolute;
left: 0%;
width: 100%;
height:100%;
}
</style>
<script>
//放大图片
function expandPhoto(){
var overlay = document.createElement("div");
overlay.setAttribute("id","overlay");
overlay.setAttribute("class","overlay");
document.body.appendChild(overlay);
var img = document.createElement("img");
img.setAttribute("class","overlayimg active");
img.setAttribute("title","点击返回");
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");
if(imgs.length>0){
imgs[0].focus();
for(var i = 0;i<imgs.length;i++){
imgs[i].onclick = expandPhoto;
imgs[i].onkeydown = expandPhoto;
}
}
}
</script>
<body>
<img class="lazy" style="width:100px;height:100px;" src="Koala.jpg" title="点击查看大图"/>
</body>
</html>