likes
comments
collection
share

React实现翻页时钟

作者站长头像
站长
· 阅读数 13

1. 布局、样式、翻页动画

    翻页时钟把数字分为上下两部分,翻页效果的实现需要通过设置 position 把所有的数组放在同一个位置叠加起来。     翻页时钟的动画是当前显示时间的 up 部分向下翻转至于屏幕垂直的位置,在这个位置需要显示的下一个时间的 down 部分向下翻转,这样就实现了翻页时钟的完整动画。

HTML 结构如下所示:

<div class="container">
    <ul class="flip">
        <li>
            <div class="up">
                <div class="content">0</div>
            </div>
            <div class="down">
                <div class="content">0</div>
            </div>
        </li>
        <li>
            <div class="up">
                <div class="content">1</div>
            </div>
            <div class="down">
                <div class="content">1</div>
            </div>
        </li>
    </ul>
</div>

CSS 样式

.container {
	height: 90px;
}
.container .flip {
	position: relative;
	float: left;
	width: 60px;
	height: 100%;
	margin: 0 5px;
}

.flip li {
	position: absolute;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	font-size: 80px;
	text-align: center;
	line-height: 90px;
	font-weight: bold;
	border-radius: 6px;
	perspective: 200px;
	transform-style: preserve-3d;
}

.flip li:first-child {
	z-index: 2;
}
// 设置class为up和down的高度为父元素容器的一半高度
.flip li > div {
	position: absolute;
	left: 0;
	height: 50%;
	width: 100%;
	overflow: hidden;
}

.flip .up {
	/* 改变选中轴的位置 使翻转轴位于up、down部分的中间*/
	transform-origin: 0 100%;
	top: 0;
	border-radius: 4px;
}

.flip .down {
	/* 改变选中轴的位置 使翻转轴位于up、down部分的中间 */
	transform-origin: 0 0;
	bottom: 0;
	border-radius: 4px;
}

.flip .content {
	position: absolute;
	width: 100%;
	border-radius: 6px;
	color: #ccc;
	background-color: #333;
	text-shadow: 0 1px 2px #000;
}

.flip .up .content {
	top: 0;
}
.flip .down .content {
	bottom: 0;
}
// 设置翻页折痕
.flip .up::after {
	content: "";
	position: absolute;
	top: 43px;
	left: 0;
	width: 100%;
	height: 4px;
	background-color: rgba(0, 0, 0, 0.4);
}

    实现的3D效果如下: React实现翻页时钟

2. 使用 JS 使动画持续翻页

    完整的翻页时钟为 00:00:00,需要翻页的有 6 个部分,可以先把翻页部分提取出单独的组件。

1、准备数据

    因为需要时分秒各个翻页部分显示的数字范围不同,所以这里先把数据准备好。

React实现翻页时钟

2、封装翻页组件

    组件接收两个参数:1、当前翻页类型(时、分、秒); 2、当前类型时间。     index 与当前类型时间相同时,当前元素的 class 为 active,上一个元素的 class 为 before;如果当前元素为第一个元素,最后一个元素的class为before。 React实现翻页时钟

3、各个翻页组件间的联动

    这里还需要定义一个对象,用于翻页组件间的联动关系的对应。 React实现翻页时钟

    秒钟的个位转完一周后,秒钟的十位需要进行一次翻页,以此类推,直到时钟的十位进行翻转。实现方式如下: React实现翻页时钟     

源码地址

stackblitz.com/edit/vitejs…