html 实现计算每篇文章多久前
时间: 2024-01-10 15:03:24 浏览: 26
要计算一篇文章发布距离当前的时间,可以使用 HTML 中的 JavaScript 实现。具体步骤如下:
1. 在 HTML 页面中,用 `<time>` 元素标记文章发布时间,格式为 ISO 8601,例如:`<time datetime="2021-07-01T10:00:00Z">2021年7月1日</time>`
2. 在 JavaScript 中获取该元素的 datetime 属性值,并将其转换为 Date 对象:`const publishedTime = new Date(document.querySelector('time').getAttribute('datetime'));`
3. 获取当前时间:`const currentTime = new Date();`
4. 计算两个时间的差值(单位为毫秒):`const diff = currentTime - publishedTime;`
5. 将差值转换为所需的时间单位,例如秒、分钟、小时、天等。
以下是一个示例代码,用于计算一篇文章发布距离当前的时间,并将结果显示在页面上:
```html
<!-- HTML 页面中 -->
<article>
<h1>文章标题</h1>
<time datetime="2021-07-01T10:00:00Z">2021年7月1日</time>
<p>文章内容</p>
<p>已发布 <span id="time-since-published"></span></p>
</article>
<script>
// JavaScript 代码
const publishedTime = new Date(document.querySelector('time').getAttribute('datetime'));
const currentTime = new Date();
const diff = currentTime - publishedTime;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
let timeSincePublished = '';
if (days > 0) {
timeSincePublished += days + ' 天 ';
}
if (hours > 0) {
timeSincePublished += hours % 24 + ' 小时 ';
}
if (minutes > 0) {
timeSincePublished += minutes % 60 + ' 分钟 ';
}
if (seconds > 0) {
timeSincePublished += seconds % 60 + ' 秒 ';
}
document.querySelector('#time-since-published').textContent = timeSincePublished + '前';
</script>
```
该示例代码将计算文章发布距离当前的时间,并将结果以“xx 天 xx 小时 xx 分钟 xx 秒 前”的格式显示在页面上。你可以根据需要修改格式或添加其它功能。