Chinese (Simplified) (中文(简体)) translation by Fish Zou (you can also view the original English article)
在前一篇文章中,我向你展示了如何从头开始创造一条响应式的垂直时间线。今天,我将介绍创建相关水平 时间线的过程。
像往常一样,为了获得一个我们将创造的东西的最初想法,浏览一下相关的CodePen示范(为了更好的体验,检查下更大的版本)
我们有很多要去介绍,所以开始吧!
1.HTML标记
这个标记与我们为垂直时间线定义的标记相同,除了三个小事情:
- 我们使用有序列表代替无序列表,因为它在语义上更正确。
- 这里有一个额外的列表项(最后一个),它是空的。在接下来的部分,我们将讨论原因。
- 这里有一个额外的元素(即
.arrows
),它负责时间线导航。
这是所需的标记:
<section class="timeline"> <ol> <li> <div> <time>1934</time> Some content here </div> </li> <!-- more list items here --> <li></li> </ol> <div class="arrows"> <button class="arrow arrow__prev disabled" disabled> <img src="arrow_prev.svg" alt="prev timeline arrow"> </button> <button class="arrow arrow__next"> <img src="arrow_next.svg" alt="next timeline arrow"> </button> </div> </section>
时间轴的初始状态看起来像这样:
2.添加CSS初始化样式
为了简便起见,在省略了一些基本的字体样式,颜色样式等之后,我们指定了一些结构化CSS规则:
.timeline { white-space: nowrap; overflow-x: hidden; } .timeline ol { font-size: 0; width: 100vw; padding: 250px 0; transition: all 1s; } .timeline ol li { position: relative; display: inline-block; list-style-type: none; width: 160px; height: 3px; background: #fff; } .timeline ol li:last-child { width: 280px; } .timeline ol li:not(:first-child) { margin-left: 14px; } .timeline ol li:not(:last-child)::after { content: ''; position: absolute; top: 50%; left: calc(100% + 1px); bottom: 0; width: 12px; height: 12px; transform: translateY(-50%); border-radius: 50%; background: #F45B69; }
最重要的是,在这里,你会注意两件事:
- 我们在列表的顶部及底部分配大的内填充。再次申明,我们将在下一部分解释为什么这么做。
- 像你在下面的案例中将会注意到的一样,我们不能看到所有的列表项,因为列表有
width:100vw
,它的父级有overflow-x:hidden
。 这有效的给列表项带上“面具”。但不管怎样,由于时间线导航的存在,我们稍后还是可以浏览这些项目的。
有了这些恰当的规则,以下是时间线的当前状态(没有任何实际内容,以保持清晰):
3.时间线元素样式
此时,我们将风格化那些既是列表项的一部分又是::before
伪元素的div
元素(从现在开始我们将称呼他们为“时间线元素”)。
此外,我们将使用:nth-child(odd)
和:nth-child(even)
CSS伪类来区分基数行和偶数行的div的样式。
这是时间线元素的常见样式:
.timeline ol li div { position: absolute; left: calc(100% + 7px); width: 280px; padding: 15px; font-size: 1rem; white-space: normal; color: black; background: white; } .timeline ol li div::before { content: ''; position: absolute; top: 100%; left: 0; width: 0; height: 0; border-style: solid; }
接着,基数行的一些样式:
.timeline ol li:nth-child(odd) div { top: -16px; transform: translateY(-100%); } .timeline ol li:nth-child(odd) div::before { top: 100%; border-width: 8px 8px 0 0; border-color: white transparent transparent transparent; }
最后,还有偶数行的一些样式:
.timeline ol li:nth-child(even) div { top: calc(100% + 16px); } .timeline ol li:nth-child(even) div::before { top: -8px; border-width: 8px 0 0 8px; border-color: transparent transparent transparent white; }
再次添加内容,时间线的新状态如下:
你可能已经注意到,时间线元素是绝对定位的。这意味着他们不是一般的文件流。 考虑到这一点,为了确保整个时间线的展示,我们为列表的顶部和底部设置大的内边距值。如果我们不采用内边距,时间线将被裁剪:

4.时间线导航样式
现在,是时候风格化导航按钮。记住,我们使往回的箭头无效,并赋予它disabled
类。
下面是相关的CSS样式:
.timeline .arrows { display: flex; justify-content: center; margin-bottom: 20px; } .timeline .arrows .arrow__prev { margin-right: 20px; } .timeline .disabled { opacity: .5; } .timeline .arrows img { width: 45px; height: 45px; }
上面的规则让我们做出了下面的时间线:
5.添加交互
时间线的基础结构搭建好了。让我们为它添加一些交互效果。
变量
重要的事情先做,我们先设置一组稍后会用到的变量。
const timeline = document.querySelector(".timeline ol"), elH = document.querySelectorAll(".timeline li > div"), arrows = document.querySelectorAll(".timeline .arrows .arrow"), arrowPrev = document.querySelector(".timeline .arrows .arrow__prev"), arrowNext = document.querySelector(".timeline .arrows .arrow__next"), firstItem = document.querySelector(".timeline li:first-child"), lastItem = document.querySelector(".timeline li:last-child"), xScrolling = 280, disabledClass = "disabled";
初始化事物
当所有页面内容加载好后,init
函数被调用。
window.addEventListener("load", init);
这个函数将触发四个子函数:
function init() { setEqualHeights(elH); animateTl(xScrolling, arrows, timeline); setSwipeFn(timeline, arrowPrev, arrowNext); setKeyboardFn(arrowPrev, arrowNext); }
我们立马会看到,每个函数都完成了某一任务。
等高时间线元素
如果返回到最近示例,你会注意到时间线元素并不等高。虽然这不影响时间线的主要功能,但是如果所有元素等高的话,你可能会更喜欢它。 为了实现这点,我们可以通过CSS赋予他们一个固定高度或通过JavaScript赋予一个和最高元素相同高度的动态高度。
第二个选项更灵活、稳定,所以这里有一个实现该行为的函数:
function setEqualHeights(el) { let counter = 0; for (let i = 0; i < el.length; i++) { const singleHeight = el[i].offsetHeight; if (counter < singleHeight) { counter = singleHeight; } } for (let i = 0; i < el.length; i++) { el[i].style.height = `${counter}px`; } }
该函数检索最高时间线元素的高度,并将其设为所有元素的高度。
示例展现如下:
6.时间线动画化
现在,让我们聚焦于时间线动画。我们将一步步建立实现该行为的函数。
首先,我们为时间线按钮做一个点击事件监听器来记录:
function animateTl(scrolling, el, tl) { for (let i = 0; i < el.length; i++) { el[i].addEventListener("click", function() { // code here }); } }
当按钮每次被点击,我们会检查时间线按钮是否处于禁用状态。如果它们不是被禁的,我们要禁用它们。这可确保只有动画完成后才能点击这两个按钮。
所以,从代码而言,单击处理程序最初包含这些行:
if (!arrowPrev.disabled) { arrowPrev.disabled = true; } if (!arrowNext.disabled) { arrowNext.disabled = true; }
接下来的步骤如下:
- 检查看看这是否是我们第一次点击按钮。再次提醒,记住Previous按钮默认是禁用的,所以我们最初唯一可点击的按钮是Next按钮。
- 如果这是第一次,我们使用
transform
属性来向右移动时间线280px。xScrolling
变量值决定移动量。 - 相反,如果我们已经点击过按钮,检索了当前时间线的
transform
值,增加或删除移动所需的量(即280px)。这样,只要我们单击Previous按钮,transform
属性的值就会减少,时间线就会从左向右移动。 然而,当点击next按钮时,transform
属性值将增加,时间线从右向左移动。
实现此功能的代码如下:
let counter = 0; for (let i = 0; i < el.length; i++) { el[i].addEventListener("click", function() { // other code here const sign = (this.classList.contains("arrow__prev")) ? "" : "-"; if (counter === 0) { tl.style.transform = `translateX(-${scrolling}px)`; } else { const tlStyle = getComputedStyle(tl); // add more browser prefixes if needed here const tlTransform = tlStyle.getPropertyValue("-webkit-transform") || tlStyle.getPropertyValue("transform"); const values = parseInt(tlTransform.split(",")[4]) + parseInt(`${sign}${scrolling}`); tl.style.transform = `translateX(${values}px)`; } counter++; }); }
干得漂亮! 我们刚刚定义了一个动画化时间线的方法。接下来的挑战是找出动画什么时候该停止。以下是我们的方法:
- 当第一个时间线元素变得完全可见,这意味着我们已经到达时间线的开始。因此我们要禁用previous按钮,还要确保next按钮可用。
- 当最后一个元素变得完全可见时,这意味着我们已经达到了时间线的结尾。因此,我们将禁用next按钮,同时确保previous按钮可用。
记得最后一个元素是一个宽度和时间线元素宽度(即280px)一致的空元素。我们赋予它这个值(或更高的)是因为我们想确保next按钮禁用前最后一个时间元素可见。
要检测目标元素在当前视口是否完全可见,我们将利用我们在垂直时间线课程中使用过的相同的代码。来自堆栈溢出线程的代码如下:
function isElementInViewport(el) { const rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); }
除了上述功能,我们定义了另一个帮手:
function setBtnState(el, flag = true) { if (flag) { el.classList.add(disabledClass); } else { if (el.classList.contains(disabledClass)) { el.classList.remove(disabledClass); } el.disabled = false; } }
此功能从一个基于flag
参数值的元素中增加或删除disabled
类。此外,它可以改变元素的禁用状态。
据上所述,我们编写的用于检查动画是否应该停止的代码如下:
for (let i = 0; i < el.length; i++) { el[i].addEventListener("click", function() { // other code here // code for stopping the animation setTimeout(() => { isElementInViewport(firstItem) ? setBtnState(arrowPrev) : setBtnState(arrowPrev, false); isElementInViewport(lastItem) ? setBtnState(arrowNext) : setBtnState(arrowNext, false); }, 1100); // other code here }); }
注意,在执行此代码之前有一个1.1秒的延迟。为什么会发生这样的事情?
如果回去看下CSS代码,我们会看到这条规定:
.timeline ol { transition: all 1s; }
所以,时间轴动画需要1秒的时间来完成。它一完成,等待100毫秒,然后执行我们的检查。
下面是带动画的时间线:
7.增加滑动支持
到目前为止,时间线不响应任何触摸事件。如果我们添加该功能,将会更好。 为了实现它,我们可以自己写下JavaScript来实现或使用一个既存的相关的库(比如:Hammer.js,TouchSwipe.js)。
为了我们的实例,我们将保持简明并使用Hammer.js,那么首先,我们把以下库包含进代码:

然后申明关联函数:
function setSwipeFn(tl, prev, next) { const hammer = new Hammer(tl); hammer.on("swipeleft", () => next.click()); hammer.on("swiperight", () => prev.click()); }
在上方函数内,我们实现了以下内容:
- 创建一个点击例子。
- 为
swipeleft
和swiperight
事件进行登记操作。 - 当我们向左扫过时间线,触发点击到下一个的按钮,时间轴因此从右向左活动。
- 当我们向右扫过时间线,触发点击先前的按钮,时间线因此从左向右活动。
带滑动支持的时间线,如下:
添加键盘导航
通过提供键盘导航支持,让我们进一步提升用户体验。我们的目标:
- 当按下左箭头键或右箭头键时,该文件应当滚动到时间线上的位置(如果另一页的部分是当前可见的)。这可以确保整个时间线是可见的。
- 具体来说,当按下左箭头键,时间线应当从左向右动画。
- 同样,当按下右箭头键,时间线应当从右向左动画。
关联函数如下所示:
function setKeyboardFn(prev, next) { document.addEventListener("keydown", (e) => { if ((e.which === 37) || (e.which === 39)) { const timelineOfTop = timeline.offsetTop; const y = window.pageYOffset; if (timelineOfTop !== y) { window.scrollTo(0, timelineOfTop); } if (e.which === 37) { prev.click(); } else if (e.which === 39) { next.click(); } } }); }
带键盘支持的时间线:
8.去响应
我们差不多要完成了!最后且重要的是,让我们确保时间线响应。当视口小于600px,它应当有以下堆叠式布局:

因为我们使用的是桌面第一的方法,我们必须重写CSS规则,如下:
@media screen and (max-width: 599px) { .timeline ol, .timeline ol li { width: auto; } .timeline ol { padding: 0; transform: none !important; } .timeline ol li { display: block; height: auto; background: transparent; } .timeline ol li:first-child { margin-top: 25px; } .timeline ol li:not(:first-child) { margin-left: auto; } .timeline ol li div { width: 94%; height: auto !important; margin: 0 auto 25px; } .timeline ol li:nth-child div { position: static; } .timeline ol li:nth-child(odd) div { transform: none; } .timeline ol li:nth-child(odd) div::before, .timeline ol li:nth-child(even) div::before { left: 50%; top: 100%; transform: translateX(-50%); border: none; border-left: 1px solid white; height: 25px; } .timeline ol li:last-child, .timeline ol li:nth-last-child(2) div::before, .timeline ol li:not(:last-child)::after, .timeline .arrows { display: none; } }
注:以上的两个规则,我们已经通过JavaScript使用了!important
规则来覆盖已应用的相关内联样式。
我们时间线的最终状态:
浏览器支持
在所有的浏览器和设备上,实例运行良好。另外,你可能注意到了,我们使用Babel来编译我们的ES6至ES5代码。
在测试时,我唯一遇到的小问题是当时间线被激活时的文本渲染变化。虽然在栈溢出线程中尝试了各种各样的被推荐的方法,但我并没有找到一种可以适应所有操作程序和浏览器的直接了当的方法。 因此,请记住,随着时间线的变化,你可能会看到小字体渲染问题。
结论
在这个相当充实的教程中,我们从一个简单的有序列表开始并制作了一个响应式水平时间线。不用怀疑,我们覆盖了大量有趣的东西,但是我希望你能享受朝着最终结果而努力的过程,这可以帮你获得一些新的知识。
如果你有任何问题或者不明白的地方,请在下方的评论栏中告诉我!
接下来的步骤
如果你想进一步提高或者延长时间线,这里有一些你可以做的小事情:
- 添加拖拽支持。我们可仅拖拽时间线区域,而不用通过点击时间按钮来导航。 对于这种行为,你能用本地拖放Api(遗憾的是在书写的时候不支持移动设备)或像Draggable.js外部库。
- 当我们调整浏览器窗口的大小时,改善时间线状态。例如,当我们调整窗口,按钮的可用及禁用状态应该不变。
- 以更易于管理的方式组织代码。或许,使用一种常见的JavaScript设计模式。
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post