Smart Time Ago 开源项目教程
项目介绍
Smart Time Ago 是一个轻量级的 jQuery 库,用于智能更新文档中的相对时间戳(例如 "3 小时前")。该项目最初是为 https://fengche.co/ 构建的,灵感来源于另一个 jQuery 插件 http://timeago.yarp.com/,但提供了更多的灵活性和智能性。Smart Time Ago 会每隔 60 秒检查并更新指定范围内的相对时间,并根据最新时间调整检查时间间隔。
项目快速启动
安装
你可以将 Smart Time Ago 作为 jQuery 插件使用。首先,将 lib/timeago.js
或 src/timeago.coffee
复制到你的项目文件夹中,然后在 jQuery 之后加载它。如果你使用 Node.js,可以通过 npm 安装:
npm install -g smart-time-ago
使用
默认情况下,Smart Time Ago 会监视带有 timeago
类和 datetime
属性的时间元素:
<time class="timeago" datetime="2012-07-18T07:51:50Z">about 8 hours ago</time>
你可以在全局初始化 Smart Time Ago:
$('body').timeago();
它将通过一个 TimeAgo 实例监视所有相对时间元素。你也可以在指定范围内使用:
<div class="timeLabels">
<time class="timeago" datetime="2012-07-18T07:51:50Z">about 8 hours ago</time>
<time class="timeago" datetime="2012-07-18T06:51:50Z">about 9 hours ago</time>
</div>
$('.timeLabels').timeago();
这将创建一个 TimeAgo 实例来更新带有 timeLabels
类的 div 中的时间元素。你也可以为每个时间元素单独创建 TimeAgo 实例。
应用案例和最佳实践
社交媒体应用
在社交媒体应用中,展示最近的评论、帖子时间是一个常见需求。使用 Smart Time Ago 可以轻松实现这一功能:
<div class="socialPosts">
<div class="post">
<time class="timeago" datetime="2023-10-01T12:00:00Z">about 1 hour ago</time>
<p>这是一个帖子内容。</p>
</div>
<div class="post">
<time class="timeago" datetime="2023-10-01T10:00:00Z">about 3 hours ago</time>
<p>这是另一个帖子内容。</p>
</div>
</div>
$('.socialPosts').timeago();
实时消息通知
在实时消息通知中,显示消息发送的时间也很重要:
<div class="notifications">
<div class="notification">
<time class="timeago" datetime="2023-10-01T12:00:00Z">about 1 hour ago</time>
<p>你有一条新消息。</p>
</div>
</div>
$('.notifications').timeago();
博客或新闻网站
在博客或新闻网站中,显示文章发表日期是基本功能:
<div class="articles">
<article>
<time class="timeago" datetime="2023-10-01T12:00:00Z">about 1 hour ago</time>
<h2>文章标题</h2>
<p>文章内容。</p>
</article>
</div>
$('.articles').timeago();
典型生态项目
Smart Time Ago 可以与其他前端框架和库无缝集成。以下是一些典型的生态项目:
jQuery
Smart Time Ago 本身就是一个 jQuery 插件,因此可以轻松与 jQuery 集成。
React
在 React 项目中,你可以使用 `react