随机图片流 Random Image Feed
1. 概述
项目本体展示了一个随机获取的图片流.
效果:
2. 结构和切图
网页的基本结构如下:
1
2
3
4
<body>
<h1>Random Image Feed</h1>
<div class="container"></div>
</body>
3. 编写 CSS
样式
首先将 body
排版方式设为水平垂直居中:
1
2
3
4
5
6
7
8
9
body {
font-family: 'Roboto', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
然后处理标题的样式:
1
2
3
4
.title {
margin: 10px 0 0;
text-align: center;
}
最后处理图片容器的样式并限定图片的尺寸:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.container {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 1000px;
}
.container img {
object-fit: cover;
margin: 10px;
height: 300px;
width: 300px;
max-width: 100%;
}
完整的 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
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
.title {
margin: 10px 0 0;
text-align: center;
}
.container {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 1000px;
}
.container img {
object-fit: cover;
margin: 10px;
height: 300px;
width: 300px;
max-width: 100%;
}
4. JavaScript
最后, 我们编写 JavaScript
函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const container = document.querySelector('.container');
const unsplashURL = 'https://source.unsplash.com/random/';
const rows = 5;
for (let i=0; i < rows * 3; i++) {
const img = document.createElement('img');
img.src = `${unsplashURL}${getRandomSize()}`;
container.appendChild(img);
}
function getRandomSize() {
return `${getRandomNr()}x%{getRandomNr()}`;
}
function getRandomNr() {
return Math.floor(Math.random() * 10) + 300;
}
最后, 完整的网页演示可见 此处