介绍
效果如下:
HTML
相册最后要补一个第一张图片的 img 元素,可以无缝循环。
1 | <div id="homeCarousel"> |
CSS
- –s CSS 变量表示相册的图片数量(不包括最后一个补上的)。
- –w CSS 变量表示相册的宽度。
- :hover 伪类控制鼠标悬浮时,停止滚动。
- animation 是 animation-name,animation-duration, animation-timing-function,animation-delay,animation-iteration-count,animation-direction,animation-fill-mode 和 animation-play-state 属性的一个简写形式。
animation: move calc(1s * var(--s)) linear infinite reverse;
的第二个参数表示 animation-duration,动画的时长,这里使用了 calc 函数,1 秒乘以相册中图片的数量;最后一个参数 animation-direction 的值 reverse 表示反向运行动画,每周期结束动画由尾到头运行。改成 normal,相册将从右向左循环滚动。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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68body {
display: grid;
place-items: center;
height: 100vh;
margin: 0;
overflow: hidden;
}
#homeCarousel {
width: 400px;
height: 240px;
line-height: 240px;
overflow: hidden;
border: solid rgba(0, 0, 0, 0.1);
}
#homeCarousel #homeCarouselWrap {
display: flex;
--w: 400;
--s: 3;
animation: move calc(1s * var(--s)) linear infinite reverse;
}
#homeCarousel #homeCarouselWrap>img {
flex-shrink: 0;
width: 100%;
height: 240px;
cursor: pointer;
vertical-align: middle;
}
@keyframes move {
0% {
transform: translate(0, 0px);
}
100% {
transform: translate(calc(var(--s) * var(--w) * -1px), 0);
}
}
#homeCarousel #homeCarouselWrap:hover {
animation-play-state: paused;
}
#modal {
position: fixed;
z-index: 1;
left: 0;
top: -100%;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.9);
transition-duration: 0.4s;
text-align: center;
}
#img2 {
width: 75%;
max-height: 80%;
}
#closeBtn {
position: absolute;
top: 5%;
right: 2.5%;
color: white;
font-size: 40px;
font-weight: bold;
cursor: pointer;
}
@media(max-width: 400px) {
#closeBtn {
top: 0;
}
}
JS
添加鼠标事件,点击相册时预览当前图片。
1 | homeCarousel.onclick = function(e) { |
马上掘金
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 张坤的博客!
评论