js实现图片放大效果
效果图
<!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>Document</title>
<style>
#body,
div,
li,
ul,
img {
margin: 0;
padding: 0;
}
#box {
width: 900px;
height: 400px;
border: 1px solid red;
position: relative;
}
ul {
display: flex;
flex-wrap: wrap;
}
li {
list-style: none;
width: 300px;
height: 200px;
}
img {
width: 100%;
height: 100%;
}
.mask {
width: 900px;
height: 400px;
background: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
}
.pic {
width: 500px;
height: 250px;
position: absolute;
left: 200px;
top: 75px;
}
span {
width: 25px;
height: 25px;
background-color: red;
text-align: center;
line-height: 25px;
position: absolute;
left: 700px;
top: 75px;
}
</style>
</head>
<body>
<div id="box">
<ul>
<!-- 插入图片 -->
<li><img src="./img/1.jpg" alt=""></li>
<li><img src="./img/2.jpg" alt=""></li>
<li><img src="./img/3.jpg" alt=""></li>
<li><img src="./img/4.jpg" alt=""></li>
<li><img src="./img/5.jpg" alt=""></li>
<li><img src="./img/6.jpg" alt=""></li>
</ul>
<!-- <div id="mask"></div>
<img class="pic" src="./img/1.jpg" alt="">
<span>X</span> -->
</div>
</body>
<script>
// 获取所有html标签
var lis = document.getElementsByTagName('li');
var box = document.getElementById('box');
for (var i = 0; i < lis.length; i++) {
// 添加点击事件
lis[i].onclick = function () {
// console.log(this);
// 创建div className = 'mask' 追加到box
var newDiv = document.createElement('div');
newDiv.className = 'mask';
box.appendChild(newDiv);
// 创建img src className 追加到box
var newImg = document.createElement('img')
newImg.className = 'pic';
newImg.src = this.getElementsByTagName('img')[0].src;
box.appendChild(newImg);
// 创建span innerHTML = X 追加到box
var newSpan = document.createElement('span');
newSpan.innerHTML = 'X';
box.appendChild(newSpan);
newSpan.onclick = function () {
box.removeChild(newDiv);
box.removeChild(newImg);
box.removeChild(newSpan);
}
}
}
</script>
</html>