JS 技能测试:图片库

题目链接

题目要求:

  • 声明一个 const 数组,用于列出每张图像的文件名,例如 'pic1.jpg'
  • 迭代数组中的文件名,为每一个文件名创建一个 <img> 元素,并将其插入到 thumb-bar <div> 中,这样图片就会嵌入页面。
  • thumb-bar <div> 里的每个 <img> 元素添加一个 click 事件监听器,在图片被点击时相应的图片将被显示到 displayed-img <img> 元素上。
  • <button> 元素添加一个 click 事件监听器,当按钮被点击时,将全尺寸图片变暗,再次点击时取消。

HTML 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">

<title>Image gallery</title>

<link rel="stylesheet" href="style.css">

</head>

<body>
<h1>Image gallery example</h1>

<div class="full-img">
<img class="displayed-img" src="images/pic1.jpg" alt="Closeup of a human eye">
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>

<div class="thumb-bar">


</div>
<script src="main.js"></script>
</body>
</html>

CSS 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
h1 {
font-family: helvetica, arial, sans-serif;
text-align: center;
}

body {
width: 640px;
margin: 0 auto;
}

.full-img {
position: relative;
display: block;
width: 640px;
height: 480px;
}

.overlay {
position: absolute;
top: 0;
left: 0;
width: 640px;
height: 480px;
background-color: rgba(0,0,0,0);
}

button {
border: 0;
background: rgba(150,150,150,0.6);
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
cursor: pointer;
top: 2px;
left: 2px;
}

.thumb-bar img {
display: block;
width: 20%;
float: left;
cursor: pointer;
}

JS 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const displayedImage = document.querySelector('.displayed-img');
const thumbBar = document.querySelector('.thumb-bar');

const btn = document.querySelector('button');
const overlay = document.querySelector('.overlay');
/* Declaring the array of image filenames */
for(let i = 1; i <= 5; i++){
const newImage = document.createElement('img');
newImage.setAttribute('src', `images/pic${i}.jpg`);
//newImage.setAttribute('alt', xxx);
newImage.onclick = ()=>{displayedImage.setAttribute('src',newImage.src);};
thumbBar.appendChild(newImage);
}
/* Declaring the alternative text for each image file */

/* Looping through images */

function updateColor(){
if(btn.getAttribute('class')==='dark'){
btn.setAttribute('class','light');
btn.textContent = 'Lighten';
overlay.style.backgroundColor = `rgba(0,0,0,0.5)`;
}
else{
btn.setAttribute('class','dark');
btn.textContent = 'dark';
overlay.style.backgroundColor = `rgba(0,0,0,0)`;
}
}
btn.onclick = updateColor;
/* Wiring up the Darken/Lighten button */