index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<!-- 展示大图 -->
<div class="main-img">
<img src="img/img1.jpg" id="current">
</div>
<!-- 展示小图 -->
<div class="imgs">
<img src="img/img1.jpg">
<img src="img/img2.jpg">
<img src="img/img3.jpg">
<img src="img/img4.jpg">
<img src="img/img5.jpg">
<img src="img/img6.jpg">
<img src="img/img7.jpg">
<img src="img/img8.jpg">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
style.css
body {
margin: 20px;
padding: 0;
background: #333;
}
.container {
max-width: 760px;
margin: auto;
border: 3px solid #fff;
background: #fff;
}
.main-img img,
.imgs img {
width: 100%;
}
.imgs {
display: grid;
/* grid-template-columns: 1fr 1fr 1fr 1fr; */
grid-template-columns: repeat(4, 1fr);
grid-gap: 5px;
}
@keyframes fadeIn {
to {
opacity: 1;
}
}
.fade-in {
opacity: 0;
animation: fadeIn 0.5s ease-in 1 forwards;
}
main.js
// 使用es6 解构赋值
/* const [current, imgs] = [
document.querySelector("#current"),
document.querySelector(".imgs img")
];
imgs.forEach(img => {
img.addEventListener("click", e => (current.src = e.target.src));
}); */
// 获取元素
const current = document.querySelector("#current");
const imgs = document.querySelectorAll(".imgs img");
const opacity = 0.4;
// 默认选中的元素图片
imgs[0].style.opacity = opacity;
imgs.forEach(img => {
img.addEventListener("click", imgClick);
});
function imgClick(e) {
// 去掉所有图片上的透明度
imgs.forEach(img => (img.style.opacity = 1));
// 拿到点击的图片路径,赋值给大图的图片路径
current.src = e.target.src;
// 动画效果 添加fadeIn类
current.classList.add("fade-in");
// 移除动画效果
setTimeout(() => current.classList.remove("fade-in"), 500);
// 给点击的图片一个透明度
e.target.style.opacity = opacity;
}
img:进入下面的网站 搜索tech
https://www.pexels.com/