
正文
JS点击img图片放大再次点击缩小JS实现 简单实用Ctrl+C+V就可以用
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
业务需要,从后台获取的图片列表,用img标签展示,用户需要查看大图。记录下来以便学习和参考.示例图如下:
放大之前:

放大之后:

点击后放大(由于图片高度超出了页面,需要通过overflow:auto;设置滚动条,点击放大图片回到列表界面)
附代码(js实现):
1、获取所有img标签,添加展开功能,该方法在图片列表加载完成以后执行:
function addExpand() {
var imgs = document.getElementsByTagName("img");
imgs[0].focus();
for(var i = 0;i<imgs.length;i++){
imgs[i].onclick = expandPhoto;
imgs[i].onkeydown = expandPhoto;
}
}
2、方法1种循环给图片的onclick和onckeydown指定了expandPhoto方法,该方法实现了点击图片放大的功能:
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("id","expand")
img.setAttribute("class","overlayimg");
img.src = this.getAttribute("src");
document.getElementById("overlay").appendChild(img); img.onclick = restore;
}
3、(style样式)方法2中,expndPhoto创建了一个id="overlay",class="overlay"的div,再给div创建了一个id="expand",class="overlayimg"的img标签,overlay和overlayimg类选择器定义如下:
<style>
.overlay{
background-color:#000; //背景色
opacity: 1.0; //不透明度
filter:alpha(opacity=100); //透明度
position: fixed;
top:0;
left:0;
width:100%;
height:100%;
z-index: 10;
overflow:auto; //滚动条
}
.overlayimg{
position: absolute;
z-index: 11;
width:99%; //宽度
height:auto; //高度自动
}
</style>
4、方法2中,给创建的img标签的onclick指定了restore方法,该方法实现了点击大图回到图片列表的功能,定义如下:
function restore(){
document.body.removeChild(document.getElementById("overlay"));
document.body.removeChild(document.getElementById("expand"));
}
5、复制粘贴即可
原文链接:https://blog.csdn.net/weixin_33890526/article/details/94694759






