Smart Time Ago 开源项目教程

Smart Time Ago 开源项目教程

smart-time-agoSmart Time Ago is a little jQuery library to update the relative timestamps in your document. 项目地址:https://gitcode.com/gh_mirrors/smar/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.jssrc/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

smart-time-agoSmart Time Ago is a little jQuery library to update the relative timestamps in your document. 项目地址:https://gitcode.com/gh_mirrors/smar/smart-time-ago

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

班歆韦Divine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值