简介
Hexo作为静态博客,访问速度还是挺快的,但是还是有局限性的,比如调用最新评论、根据点击量和评论数进行热门文章排序等等。最近几天,在icraus主题的魔改版amazing主题上看到了最新评论的调用,适用于valine和gitalk,就想把这个功能移植过来,于是就有了这样一个最初的版本:
本文调用Valine最新评论的代码,是在水寒博客的评论调用的基础上,增加了一下功能:
- 评论者网址
- 评论定位链接
- 博主判断
评论头像显示感觉没啥必要,但功能可以实现
9月4日更新:
修改为保姆级教程,附上修改位置图。见修改思路。
使用方法
引用文件
这个是leancloud sdk,必须在最开始调用,否则会报错
//cdn.jsdelivr.net/npm/leancloud-storage@3/dist/av-min.js
接下来就是valine.js的调用,这个主题都自带
//cdn.jsdelivr.net/npm/valine@1.4/dist/Valine.min.js
js核心代码
把功能代码封装成名为 newcomment()
的函数:
function newcomment() {
function queryLeanCloud(k) {
let root = this;
let len = arguments.length;
if (len == 1) {
let notExist = new AV.Query("Comment");
notExist.doesNotExist('rid');
let isEmpty = new AV.Query("Comment");
isEmpty.equalTo('rid', '');
let q = AV.Query.or(notExist, isEmpty);
if (k === '*') q.exists('url');
else q.equalTo('url', decodeURI(k));
q.addDescending('createdAt');
q.addDescending('insertedAt');
return q;
} else {
let ids = JSON.stringify(arguments[1]).replace(/(\[|\])/g, '');
let cql = `select * from ${root['config']['clazzName']} where rid in (${ids}) order by -createdAt,-createdAt`;
return AV.Query.doCloudQuery(cql)
}
}
var valine = new Valine({
el: '#valine_container_ba(因为主题已经有valine的这些参数了,这里随意填都行)',
app_id: '换成自己的leancloud appid',
app_key: '换成自己的',
placeholder: '',
serverURLs: '换成自己的api'
});
//判断博主,heson改为自己的昵称
function bozhu(e){
if (e == "heson"){
nick = e + '[博主]'
return nick;
} else {
return e
}
}
//判断网址
function wangzhi(e){
http = e.slice(0,4)
https = e.slice(0,5)
if (http == "http" || https == "https" ){
return e
} else if (e == "" || e == null || e == undefined){
return e
} else {
e = 'http://'+ e
return e
}
}
//查询评论
valine.Q('*').limit(7).find().then(function (comments) {
var hotComments = $("#hot-comments");
for (var i = 0; i < comments.length; i++) {
if (i === 0) {
console.log(comments[0]);
}
var nick = bozhu(comments[i]._serverData.nick);
var content = comments[i]._serverData.comment;
var newcontent = content.substring(0, 50).replace(/<[^>]+>/g,"");
var url = comments[i]._serverData.url;
var link = wangzhi(comments[i]._serverData.link);
var updatedAt = timeago(comments[i].updatedAt);
var commentId = '#' + comments[i].id;
hotComments.append('<div class="card-comment-item"><div class="item-header-text"><a href="'+ link +'" target="_blank" rel="nofollow noopener noreferrer" class="newcomment" >' + nick + '</a> 发表于' + updatedAt + '</div><div class="item-text"><a href="' + url + commentId +'" rel="nofollow" style="color:#717171" class="comments-detail" >' + newcontent + '</a></div></div>');
}
});
};
注意在判断博主的位置,需要改成自己评论的昵称。
在content.substring(0, 50)
处是截断评论字数,这里设置为50个英文字符长度。
通过F12控制台可以看到,这里还能根据邮箱信息,调用头像参数,但我就没写上去了,感觉没什么必要,如图所示:
css 代码
每个评论底部加上分割线用于区分,发表时间淡化字体颜色,链接hover用的主题的颜色,要改的基本就这些,如果含有头像的话,可以设置鼠标悬停显示,这样效果也挺不错,动手能力强的小伙伴可以自己加:
.card-comment-item
margin:10px 0 10px 0
border-bottom: 1px solid #e2dada
padding-bottom:5px
.item-header-text
color:#9a9a9a
.item-text
margin-top:5px
padding:0
a.newcomment{
font-weight:bold;
color:#444;
}
a.newcomment:hover{
color:#36ac91!important;
}
a.comments-detail:hover{
color:#36ac91!important;
}
修改思路
- 核心js代码加载
themes\volantis\layout\_third-party\comments\valine\script.ejs
因为开启了pjax,
newcomment()
的调用放在themes\volantis\layout\_third-party\pjax\index.ejs
CSS直接丢在main.styl里了
主题配置里面要加上通用文本栏目,核心是
id为hot-comments的div框
,js要通过这个id进行渲染,代码如下:newcomment: class: text display: [desktop] # [desktop, mobile] header: icon: far fa-comments title: 最新评论 url: content: - '<div id="hot-comments"></div>'
代码更新
10月1日:
最新的cuteen主题(hexo移植版)我加上了头像的调用(下面列出修改部分):
//获取头像
function getAvater(mail){
var a = mail.slice(-5,-6)
return '//v1.alapi.cn/api/avatar?email='+mail+'&size=100'
}
//查询评论
valine.Q('*').limit(7).find().then(function (comments) {
var hotComments = $("#hot-comments");
for (var i = 0; i < comments.length; i++) {
if (i === 0) {
console.log(comments[0]);
}
var nick = bozhu(comments[i]._serverData.nick);
var content = comments[i]._serverData.comment;
var newcontent = content.replace(/<[^>]+>/g,"").substring(0, 50);
var url = comments[i]._serverData.url;
var mail = getAvater(comments[i]._serverData.mail);
var link = wangzhi(comments[i]._serverData.link);
var updatedAt = timeago(comments[i].updatedAt);
var commentId = '#' + comments[i].id;
hotComments.append('<li class="px1 pb2 flex items-center"><img style="width: 40px;height:40px" class="circle mx1 listavatar" src="'+mail+'"><div class="w100"><div class="flex justify-between"><div class="h6 listauthor overflow-hidden" title="' + nick + '"><a target="_blank" rel="noopener external nofollow noreferrer" href="' + link + '">' + nick + '</a></div><span class="h6 mr1 listdate wenzi hang1">' + updatedAt + '</span></div> <a href="' + url + commentId +'"><div class="h5 list-comcontent overflow-hidden">' + newcontent + '</div></a></div></li>');
}
});
10月18日:
部分童鞋调用成功但是不显示,是因为没有timeago()这个友好显示时间的函数,需把下面代码加在//查询评论
代码之前:
function timeago(dateTimeStamp) {
var minute = 1000 * 60; //把分,时,天,周,半个月,一个月用毫秒表示
var hour = minute * 60;
var day = hour * 24;
var week = day * 7;
var month = day * 30;
var now = new Date().getTime(); //获取当前时间毫秒
var diffValue = now - dateTimeStamp; //时间差
if (diffValue < 0) {
return;
}
var minC = diffValue / minute; //计算时间差的分,时,天,周,月
var hourC = diffValue / hour;
var dayC = diffValue / day;
var weekC = diffValue / week;
var monthC = diffValue / month;
if (monthC >= 1 && monthC <= 3) {
result = " " + parseInt(monthC) + " 月前"
} else if (weekC >= 1 && weekC <= 3) {
result = " " + parseInt(weekC) + " 周前"
} else if (dayC >= 1 && dayC <= 6) {
result = " " + parseInt(dayC) + " 天前"
} else if (hourC >= 1 && hourC <= 23) {
result = " " + parseInt(hourC) + " 小时前"
} else if (minC >= 1 && minC <= 59) {
result = " " + parseInt(minC) + " 分钟前"
} else if (diffValue >= 0 && diffValue <= minute) {
result = "刚刚"
} else {
var datetime = new Date();
datetime.setTime(dateTimeStamp);
var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
result = Nmonth + "-" + Ndate
}
return result;
}