博客园评论区头像换页更新解决方案

前言

博客园博客正文的评论区的每一条评论其实都是带用户头像链接的,因此有些博客主题利用这个链接,对评论新增了头像显示功能。

但是这部分功能只能在第一次加载页面时有效,一旦出现评论翻页、排序等操作,头像又没了。

为了解决这个问题 ,使用 MutationObserver#blog-comments-placeholder 这个元素进行改动监控,一旦有变动则再次执行一次头像设置函数。

实现过程

头像设置函数 setAvatar

/* 头像设置 */
setAvatar = function () {
// 头像
$.each($(".feedbackItem"), function (index, ele) {
var self = $(ele);
// 已经处理过了的则跳过
if (self.find('comment_avatar_container').length > 0)
{
return;
}
// 这里自己定义需要如何设置评论区头像可自行修改
var obj = self.find(".blog_comment_body");
var id = obj.attr("id").split("_")[2];
var blog = self.find('a[id^="a_comment_author"]');
var blogUrl = blog.attr("href");
var imgSrc =
$("#comment_" + id + "_avatar").html() ||
"http://pic.cnblogs.com/avatar/simple_avatar.gif";
self.prepend(
'<a class="comment_avatar_container" target="_blank" href="' +
blogUrl +
'"><img src="' +
imgSrc +
'" style="float:left;" class="comment_avatar"></a>'
);
$(".feedbackListSubtitle").addClass("feedbackListSubtitle_right");
$(".feedbackCon").addClass("feedbackCon_right");
});
}

头像更新 updateAvatar

/* 头像更新 */
updateAvatar = function()
{
// 获取要监控的元素
const targetNode = document.getElementById('blog-comments-placeholder');
// 创建一个 MutationObserver 实例,并定义回调函数
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
// console.log('A child node has been added or removed.');
setAvatar();
} else if (mutation.type === 'attributes') {
// console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
});
// 配置观察选项
const config = {
attributes: true,
childList: true,
subtree: false // 观察目标节点及其后代节点
};
// 启动观察
observer.observe(targetNode, config);
}

评论区设置 setComment

/* 评论区 */
setComment = function () {
setAvatar();
updateAvatar();
};

页脚代码

<script>
$(function () {
setComment();
});
</script>

效果测试

点击本博客评论数最多的博文进行查看:https://www.cnblogs.com/gshang/p/biliTheme.html#!comments

提炼

这里的监控变化其实可以提炼为一个通用的根据监控元素改变来更新某动作的函数:

updateContentOnChange = function(targetNode, action)
{
// 获取要监控的元素
// 创建一个 MutationObserver 实例,并定义回调函数
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
// console.log('A child node has been added or removed.');
action();
} else if (mutation.type === 'attributes') {
// console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
});
// 配置观察选项
const config = {
attributes: true,
childList: true,
subtree: false // 观察目标节点及其后代节点
};
// 启动观察
observer.observe(targetNode, config);
}
posted @   GShang  阅读(164)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-09-16 研究生数学建模比赛日程安排
2019-09-16 博客园主题定制
点击右上角即可分享
微信分享提示