2862 lines
98 KiB
JavaScript
2862 lines
98 KiB
JavaScript
var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
|
||
var storage = window.localStorage;
|
||
|
||
var lazyLoadInstance = new LazyLoad({});
|
||
|
||
$(document).on('click', '.left_menu_box ul li a , .widget_nav_menu ul li a, .menu-top-container ul li a', function () {
|
||
var t = $(this);
|
||
t.siblings("ul").slideToggle(200);
|
||
t.parent().siblings().find("ul").hide(200);
|
||
if (t.parent().hasClass('has_children')) {
|
||
t.find('.drop_icon').toggleClass('up');
|
||
}
|
||
$('.left_menu_box ul li').removeClass('current-pjax-item current-menu-item current-menu-parent current-menu-ancestor');
|
||
t.parent().addClass('current-pjax-item');
|
||
});
|
||
|
||
var route = location.href.substring(0, location.href.indexOf('?') === -1 ? (location.href.indexOf('#') === -1 ? location.href.length : location.href.indexOf('#')) : location.href.indexOf('?'))
|
||
|
||
$('.left_menu_box ul li a').each((i, e) => {
|
||
if (e.parentElement.childNodes.length > 3) {
|
||
return
|
||
}
|
||
let href = e.href.substring(0, e.href.indexOf('?') === -1 ? (e.href.indexOf('#') === -1 ? e.href.length : e.href.indexOf('#')) : e.href.indexOf('?'))
|
||
if (route === href) {
|
||
e.parentElement.classList.add('current-pjax-item')
|
||
}
|
||
})
|
||
$('.left_menu_box ul li ul li a').each((i, e) => {
|
||
let href = e.href.substring(0, e.href.indexOf('?') === -1 ? (e.href.indexOf('#') === -1 ? e.href.length : e.href.indexOf('#')) : e.href.indexOf('?'))
|
||
if (route === href) {
|
||
e.parentElement.parentElement.parentElement.classList.add('current-pjax-item')
|
||
}
|
||
})
|
||
|
||
|
||
//全局loading
|
||
function loading_template() {
|
||
tag = '<div class="loader" uk-spinner></div>';
|
||
tag += '</div>';
|
||
|
||
return tag;
|
||
}
|
||
|
||
function loading_start(target) {
|
||
target.append(loading_template());
|
||
}
|
||
|
||
function loading_done(target) {
|
||
target.children('.loader').remove();
|
||
}
|
||
|
||
|
||
//话题表情添加
|
||
$(document).on('click', 'a.smile_btn', function () {
|
||
var a = $(this).html();
|
||
var textarea = $("textarea#topic_content");
|
||
var content = textarea.val();
|
||
textarea.val(content + a);
|
||
textarea.focus();
|
||
});
|
||
|
||
$(document).on('click', '.smile_box i', function () {
|
||
var t = $(".smile_show");
|
||
t.slideToggle(100);
|
||
});
|
||
//选择话题
|
||
$(document).on('click', '.t_cat_box li', function () {
|
||
var name = $(this).find('.c_name span').html();
|
||
$('.t_cat_toogle span').html(name);
|
||
|
||
UIkit.dropdown('.t_cat_box').hide(false);
|
||
});
|
||
|
||
$(document).on('click', '.up_cat_btn', function () {
|
||
var name = $('input#add_cat').val();
|
||
if (!name) {
|
||
cocoMessage.error("请填写话题");
|
||
return false;
|
||
}
|
||
$('.t_cat_toogle span').text(name)
|
||
UIkit.dropdown('.t_cat_box').hide(false);
|
||
});
|
||
|
||
$(document).on('click', '.simi a', function () {
|
||
var visible = $(this).attr('visible');
|
||
if (visible == 'PUBLIC') {
|
||
$(this).html('<i class="ri-lock-line"></i>').attr('visible', 'PRIVATE');
|
||
$(this).children().css({ "background": "#ddd", "color": "#c6c6c6" });
|
||
} else {
|
||
$(this).html('<i class="ri-lock-unlock-line"></i>').attr('visible', 'PUBLIC');
|
||
$(this).children().css({ "background": "#e3efe7", "color": "#66c187" });
|
||
}
|
||
});
|
||
|
||
//消息通知
|
||
cocoMessage.config({
|
||
duration: 2000,
|
||
});
|
||
|
||
//sortable事件 隐藏input
|
||
UIkit.util.on('.img_show', 'start', function (item) {
|
||
$(".up_img_btn").hide();
|
||
});
|
||
UIkit.util.on('.img_show', 'moved', function (item) {
|
||
var img_num = $('.add_img_box .t_media_item').length;
|
||
if (img_num < 9) {
|
||
$(".up_img_btn").show();
|
||
}
|
||
|
||
});
|
||
UIkit.util.on('.img_show', 'stop', function (item) {
|
||
var img_num = $('.add_img_box .t_media_item').length;
|
||
if (img_num < 9) {
|
||
$(".up_img_btn").show();
|
||
}
|
||
});
|
||
|
||
|
||
//ajax上传媒体文件到媒体库(已兼容图片/视频)
|
||
$(document).on('change', '#topic_img_up', function (e) {
|
||
e.preventDefault();
|
||
if ($('#topic_img_up').val() == '') return;
|
||
|
||
const policyName = Theme.moments.policy_name;
|
||
const groupName = Theme.moments.group_name;
|
||
|
||
var files = $('#topic_img_up')[0].files;
|
||
var imgtot = 0;
|
||
var num = $('.add_img_box .t_media_item').length;
|
||
|
||
// 修改提示语为“文件”
|
||
if (num + files.length > 9) {
|
||
cocoMessage.error("最多上传9个媒体文件");
|
||
return;
|
||
}
|
||
|
||
$.each(files, function (i, file) {
|
||
imgtot += file['size'];
|
||
});
|
||
|
||
var tot = imgtot / 1024000;
|
||
|
||
$(".up_img_btn i").hide();
|
||
$(".up_img_btn").prepend("<div class='img_load_text'><div uk-spinner='ratio: .6'></div><span>"
|
||
+ tot.toFixed(2) + "MB</span></div>");
|
||
|
||
$.each(files, function (i, file) {
|
||
var data = new FormData();
|
||
data.append('file', file);
|
||
policyName && data.append('policyName', policyName);
|
||
groupName && data.append('groupName', groupName);
|
||
|
||
$.ajax({
|
||
type: "POST",
|
||
url: `${Theme.moments.attachments_upload_api}`,
|
||
dataType: 'json',
|
||
data: data,
|
||
processData: false,
|
||
contentType: false,
|
||
beforeSend: function () {
|
||
$('input#topic_img_up').attr('disabled', 'disabled');
|
||
},
|
||
success: function (data) {
|
||
// 1. 获取上传后的地址
|
||
var src = data.metadata.annotations["storage.halo.run/uri"]
|
||
|| data.metadata.annotations["storage.halo.run/external-link"]
|
||
|| data.metadata.annotations["lskypro.plugin.halo.chenhe.me/image-link"];
|
||
|
||
// 2. 获取文件类型 (MIME Type)
|
||
// Halo 的 API 通常在 data.spec.mediaType 中返回类型,或者根据后缀判断
|
||
var mediaType = data.spec.mediaType || "";
|
||
var isVideo = mediaType.startsWith('video/') || /\.(mp4|webm|mov)$/i.test(src);
|
||
|
||
// 3. 动态生成预览 HTML
|
||
var mediaInner = isVideo
|
||
? `<video src="${src}" class="pix_video" preload="metadata" muted></video>`
|
||
: `<img src="${src}">`;
|
||
|
||
var media = `<div class="t_media_item" data-src="${src}" data-type="${mediaType}" data-thum="${src}">
|
||
<a class="topic-img-de"><i class="ri-subtract-line"></i></a>
|
||
${mediaInner}
|
||
</div>`;
|
||
|
||
$(".img_show").prepend(media);
|
||
|
||
num = $('.add_img_box .t_media_item').length;
|
||
$(".img_load_text").remove();
|
||
|
||
if (num < 10) $(".up_img_btn i").show();
|
||
$('input#topic_img_up').removeAttr('disabled');
|
||
},
|
||
error: function () {
|
||
cocoMessage.error("上传失败");
|
||
$(".img_load_text").remove();
|
||
$(".up_img_btn i").show();
|
||
$('input#topic_img_up').removeAttr('disabled');
|
||
}
|
||
});
|
||
});
|
||
});
|
||
|
||
//同步修改检查数量的提示语
|
||
function check_image_num() {
|
||
var num = $('.add_img_box .t_media_item').length;
|
||
if (num > 8) {
|
||
cocoMessage.error("最多上传9个媒体文件");
|
||
return true;
|
||
}
|
||
}
|
||
|
||
//sortable事件 隐藏input
|
||
UIkit.util.on('.img_show', 'start', function (item) {
|
||
$(".up_img_btn").hide();
|
||
});
|
||
UIkit.util.on('.img_show', 'moved', function (item) {
|
||
var img_num = $('.add_img_box .t_media_item').length;
|
||
if (img_num < 9) {
|
||
$(".up_img_btn").show();
|
||
}
|
||
|
||
});
|
||
UIkit.util.on('.img_show', 'stop', function (item) {
|
||
var img_num = $('.add_img_box .t_media_item').length;
|
||
if (img_num < 9) {
|
||
$(".up_img_btn").show();
|
||
}
|
||
});
|
||
|
||
//获取媒体库图片/视频(功能不变)
|
||
$(document).on('click', '.up_from_media a', function () {
|
||
$(".attch_nav .pre").hide();
|
||
$(".attch_nav .nex").hide();
|
||
$(".attch_nav").attr('paged', '1');
|
||
$(".wp_get_media_list").empty();
|
||
$(".show_media_box").show();
|
||
$.ajax({
|
||
type: "get",
|
||
url: `/apis/${Theme.moments.attachments_api}/v1alpha1/attachments?group=&page=1&size=10&ungrouped=false&accepts=image/*&accepts=video/*`,
|
||
contentType: "application/json",
|
||
beforeSend: function () { },
|
||
success: function (data) {
|
||
var list = data.items;
|
||
$.each(list, function (i, value) {
|
||
var thum = value.status.permalink;
|
||
var src = value.status.permalink;
|
||
var mediaType = value.spec.mediaType || '';
|
||
var wf_media = '';
|
||
|
||
if (mediaType.startsWith('video/')) {
|
||
wf_media = `<li data-src="${src}" data-type="${mediaType}">
|
||
<video class="media-video-thumb" src="${src}" preload="metadata" muted></video>
|
||
</li>`;
|
||
} else {
|
||
wf_media = `<li data-src="${src}" data-type="${mediaType}">
|
||
<img src="${thum}">
|
||
</li>`;
|
||
}
|
||
$(".wp_get_media_list").append(wf_media);
|
||
});
|
||
var max = data.totalPages;
|
||
$(".attch_nav .nex").toggle(max > 1);
|
||
}
|
||
});
|
||
});
|
||
|
||
//媒体库分页(功能不变)
|
||
$(document).on('click', '.attch_nav a', function () {
|
||
$(".wp_get_media_list").empty();
|
||
var type = $(this).attr('class');
|
||
var paged = $(".attch_nav").attr('paged');
|
||
|
||
if (type == 'nex') {
|
||
paged = parseInt(paged) + 1;
|
||
} else if (type == 'pre' && paged) {
|
||
paged = parseInt(paged) - 1;
|
||
}
|
||
|
||
$(".attch_nav").attr('paged', paged);
|
||
$.ajax({
|
||
type: "get",
|
||
url: `/apis/${Theme.moments.attachments_api}/v1alpha1/attachments?group=&page=${paged}&size=10&ungrouped=false&accepts=image/*&accepts=video/*`,
|
||
contentType: "application/json",
|
||
beforeSend: function () { },
|
||
success: function (data) {
|
||
$(".wp_get_media_list").empty();
|
||
var list = data.items;
|
||
$.each(list, function (i, value) {
|
||
var thum = value.status.permalink;
|
||
var src = value.status.permalink;
|
||
var mediaType = value.spec.mediaType;
|
||
var wf_media = '';
|
||
|
||
if (mediaType.startsWith('video/')) {
|
||
wf_media = `<li data-src="${src}" data-type="${mediaType}">
|
||
<video class="media-video-thumb" src="${src}" preload="metadata" muted></video>
|
||
</li>`;
|
||
} else {
|
||
wf_media = `<li data-src="${src}" data-type="${mediaType}">
|
||
<img src="${thum}">
|
||
</li>`;
|
||
}
|
||
$(".wp_get_media_list").append(wf_media);
|
||
});
|
||
|
||
var max = data.totalPages;
|
||
$(".attch_nav .nex").toggle(max > paged);
|
||
$(".attch_nav .pre").toggle(paged > 1);
|
||
}
|
||
});
|
||
});
|
||
|
||
//收起媒体库(无修改)
|
||
$(document).on('click', '.show_media_box .souqi', function () {
|
||
$(".show_media_box").hide();
|
||
$(".wp_get_media_list").empty();
|
||
});
|
||
|
||
//从媒体库插入图片/视频(删除按钮样式简化)
|
||
$(document).on('click', '.wp_get_media_list li', function () {
|
||
var num = $('.add_img_box .t_media_item').length;
|
||
if (num == 8) {
|
||
$("a.up_img_btn").hide();
|
||
}
|
||
if (check_image_num()) {
|
||
return false;
|
||
}
|
||
|
||
var src = $(this).attr('data-src');
|
||
var type = $(this).attr('data-type');
|
||
var mediaHtml = '';
|
||
|
||
if (type.startsWith('video/')) {
|
||
mediaHtml = `<div class="t_media_item" data-src="${src}" data-type="${type}">
|
||
<a class="topic-img-de"><i class="ri-subtract-line"></i></a>
|
||
<video src="${src}" class="pix_video" preload="metadata" muted></video>
|
||
</div>`;
|
||
} else {
|
||
var thum = $(this).children().attr('src') || $(this).children().attr('poster');
|
||
mediaHtml = `<div class="t_media_item" data-src="${src}" data-thum="${thum}" data-type="${type}">
|
||
<a class="topic-img-de"><i class="ri-subtract-line"></i></a>
|
||
<img src="${thum}">
|
||
</div>`;
|
||
}
|
||
$(".img_show").prepend(mediaHtml);
|
||
});
|
||
|
||
//删除图片/视频(保留事件冒泡修复)
|
||
$(document).on('click', '.topic-img-de', function (e) {
|
||
e.stopPropagation();
|
||
|
||
var msg = "确认删除此媒体文件?";
|
||
if (confirm(msg)) {
|
||
$(this).parent().remove();
|
||
} else {
|
||
return false;
|
||
}
|
||
var num = $('.add_img_box .t_media_item').length;
|
||
if (num < 9) {
|
||
$("a.up_img_btn").show();
|
||
}
|
||
});
|
||
|
||
// 样式修复:3列布局 + 正方形显示(核心)
|
||
$(function () {
|
||
var style = `<style>
|
||
/* 媒体库视频封面:正方形显示,和图片一致 */
|
||
.media-video-thumb {
|
||
width: 100%;
|
||
height: 100%;
|
||
object-fit: cover; /* 裁剪为正方形,不拉伸 */
|
||
border: none;
|
||
pointer-events: none;
|
||
}
|
||
/* 媒体库li:适配3列,强制正方形 */
|
||
.wp_get_media_list li {
|
||
position: relative;
|
||
display: inline-block;
|
||
width: calc(33.333% - 10px); /* 3列基础宽度 */
|
||
aspect-ratio: 1/1; /* 强制正方形(宽高比1:1) */
|
||
margin: 5px;
|
||
overflow: hidden; /* 裁剪超出部分 */
|
||
vertical-align: top;
|
||
}
|
||
|
||
/* 核心:.t_media_item 强制正方形 + 3列布局 */
|
||
.t_media_item {
|
||
position: relative !important;
|
||
display: inline-block !important;
|
||
width: calc(33.333% - 10px) !important; /* 3列宽度,和原有布局一致 */
|
||
aspect-ratio: 1/1 !important; /* 强制正方形,覆盖视频原比例 */
|
||
margin: 5px !important;
|
||
overflow: hidden !important; /* 裁剪超出的视频内容 */
|
||
vertical-align: top !important;
|
||
touch-action: none !important;
|
||
user-select: none !important;
|
||
}
|
||
/* 删除按钮:固定在正方形右上角 */
|
||
.t_media_item .topic-img-de {
|
||
position: absolute !important;
|
||
top: 5px !important;
|
||
right: 5px !important;
|
||
background: rgba(0,0,0,0.5) !important;
|
||
color: #fff !important;
|
||
width: 20px !important;
|
||
height: 20px !important;
|
||
border-radius: 50% !important;
|
||
display: flex !important;
|
||
align-items: center !important;
|
||
justify-content: center !important;
|
||
text-decoration: none !important;
|
||
z-index: 99 !important;
|
||
pointer-events: auto !important;
|
||
}
|
||
/* 视频/图片:裁剪为正方形,不拉伸 */
|
||
.t_media_item video, .t_media_item img {
|
||
width: 100% !important;
|
||
height: 100% !important;
|
||
object-fit: cover !important; /* 关键:裁剪多余部分,保持正方形 */
|
||
display: block !important;
|
||
}
|
||
</style>`;
|
||
$('head').append(style);
|
||
});
|
||
|
||
//插入外部图片链接
|
||
$(document).on('click', '.up_from_cdn a', function () {
|
||
//$(".show_media_box .souqi").click();
|
||
$(".show_cdn_media").show();
|
||
|
||
});
|
||
|
||
//取消
|
||
$(document).on('click', 'a.img_link_cancel', function () {
|
||
$(".show_cdn_media").hide();
|
||
});
|
||
|
||
//插入图片或视频链接
|
||
$(document).on('click', 'a.img_link_btn', function () {
|
||
var img_url = $("#img_link_up").val().trim();
|
||
|
||
// 1. 扩展正则判断,支持视频后缀
|
||
if (!/\.(mp4|webm|jpg|png|gif|webp|jpeg)$/i.test(img_url) || img_url == '') {
|
||
cocoMessage.error("媒体格式不正确或链接为空!");
|
||
return false;
|
||
}
|
||
|
||
if (check_image_num()) {
|
||
return false;
|
||
}
|
||
|
||
var num = $('.add_img_box .t_media_item').length;
|
||
if (num == 8) {
|
||
$("a.up_img_btn").hide();
|
||
}
|
||
|
||
var src = img_url;
|
||
// 获取后缀名并转为小写
|
||
var ext = img_url.substring(img_url.lastIndexOf('.') + 1).toLowerCase();
|
||
|
||
// 2. 判定是否为视频
|
||
var isVideo = (ext === 'mp4' || ext === 'webm');
|
||
var type = isVideo ? 'video/' + ext : 'image/' + ext;
|
||
|
||
// 3. 根据类型生成预览 HTML
|
||
var mediaPreview = '';
|
||
if (isVideo) {
|
||
mediaPreview = `<video src="${src}" class="pix_video" preload="metadata" muted></video>`;
|
||
} else {
|
||
mediaPreview = `<img src="${src}">`;
|
||
}
|
||
|
||
var media = `<div class="t_media_item" data-src="${src}" data-thum="${src}" data-type="${type}">
|
||
<a class="topic-img-de"><i class="ri-subtract-line"></i></a>
|
||
${mediaPreview}
|
||
</div>`;
|
||
|
||
$(".img_show").prepend(media);
|
||
$("#img_link_up").val('');
|
||
});
|
||
|
||
//ajax获取我的地理位置
|
||
$(document).on('click', '.loca .laqu', function () {
|
||
var gaode_key = Theme.moments.gaode_key;
|
||
var ip = '';
|
||
$.ajax({
|
||
type: "get",
|
||
url: `/apis/uc.api.security.halo.run/v1alpha1/devices`,
|
||
contentType: "application/json",
|
||
success: function (data) {
|
||
if (data.length > 0) {
|
||
var ipAddress = data[0].device.spec.ipAddress;
|
||
if (!/^10\.|^192\.|^168\.|^172\./.test(ipAddress)) {
|
||
ip = data[0].device.spec.ipAddress
|
||
}
|
||
}
|
||
$.ajax({
|
||
type: "get",
|
||
url: `https://restapi.amap.com/v3/ip?ip=${ip}&key=${gaode_key}`,
|
||
contentType: "application/json",
|
||
beforeSend: function () {
|
||
$(".loca_text").text("数据拉取中..");
|
||
},
|
||
success: function (data) {
|
||
if (data.status == '1') {
|
||
var city = 'X市';
|
||
if (typeof data.city === 'string') {
|
||
city = data.city;
|
||
}
|
||
var province = 'X省';
|
||
if (typeof data.province === 'string') {
|
||
province = data.province;
|
||
}
|
||
var loca = "" + province + " · " + city + "";
|
||
$(".loca_text").html(loca).attr("state", '1'); //设置为开启
|
||
} else {
|
||
cocoMessage.error(data.info);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
});
|
||
});
|
||
|
||
//插入自定义位置【点击关闭】
|
||
$(document).on('click', 'a.set_local_btn', function (e) {
|
||
var loca = $("#set_local").val();
|
||
var state = $(".loca_text").attr('state');
|
||
if (loca == '') {
|
||
cocoMessage.error("为空则不显示位置");
|
||
$(".loca_text").text('').attr("state", '0');
|
||
$("a.close_local").text('位置已关闭').css('color', '#ddd');
|
||
$.removeCookie('mylocal', { path: '/' });
|
||
} else {
|
||
$(".loca_text").text(loca).attr("state", '1');
|
||
$("a.close_local").text('位置已开启').css('color', '#8890cc');
|
||
$.cookie('mylocal', loca, { expires: 30, path: '/' });
|
||
}
|
||
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
UIkit.dropdown($('.local_box')).hide(0);
|
||
});
|
||
|
||
//插入自定义位置【input监控】
|
||
$(document).on('input', '#set_local', function () {
|
||
var loca = $(this).val();
|
||
var state = $(".loca_text").attr('state');
|
||
|
||
if (loca == '') {
|
||
cocoMessage.error("为空则不显示位置");
|
||
$(".loca_text").text('').attr("state", '0');
|
||
$("a.close_local").text('位置已关闭').css('color', '#ddd');
|
||
} else {
|
||
$(".loca_text").text(loca).attr("state", '1');
|
||
$("a.close_local").text('位置已开启,点击关闭').css('color', '#8890cc');
|
||
}
|
||
});
|
||
|
||
//关闭地理位置
|
||
$(document).on('click', 'a.close_local', function () {
|
||
$(".loca_text").text('').attr("state", '0');
|
||
$('#set_local, [name="set_local"]').val('');
|
||
$("a.close_local").text('位置已关闭').css('color', '#ddd');
|
||
});
|
||
|
||
$(document).on('click', '.loca_text', function () {
|
||
$("a.close_local").text('位置已开启,点击关闭').css('color', '#8890cc');
|
||
});
|
||
|
||
//发布更新瞬间
|
||
let isSubmittingMoment = false;
|
||
$(document).on('click', '.push_item', function () {
|
||
|
||
if (isSubmittingMoment) return false;
|
||
|
||
var content = $("#topic_content").val();
|
||
var catname = $(".t_cat_toogle span").text();
|
||
var loca = $(".loca_text").text();
|
||
var act = $('.push_item').attr('action');
|
||
var pid = $('.push_item').attr('pid');
|
||
var moment_type = $('.push_item').attr('type');
|
||
var visible = $(".simi a").attr('visible');
|
||
var min = Theme.moments.min_push_num;
|
||
|
||
if (min > 0) {
|
||
if (!content) {
|
||
cocoMessage.error("请输入内容");
|
||
return false;
|
||
}
|
||
if (content.length < min) {
|
||
cocoMessage.error("内容不得少于" + min + "个字");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
let tags = [];
|
||
if (catname) {
|
||
tags.push(catname);
|
||
content += `<p><a class="tag" href="?tag=${catname}" data-pjax="">${catname}</a></p>`;
|
||
}
|
||
|
||
get_moment_data(moment_type);
|
||
|
||
isSubmittingMoment = true;
|
||
|
||
const $btn = $(this);
|
||
$btn.attr('disabled', true).addClass('disabled');
|
||
|
||
function release() {
|
||
isSubmittingMoment = false;
|
||
$btn.removeAttr('disabled').removeClass('disabled');
|
||
}
|
||
|
||
if (act === 'push') {
|
||
|
||
let pushData = {
|
||
apiVersion: 'moment.halo.run/v1alpha1',
|
||
kind: 'Moment',
|
||
metadata: { generateName: "moment-" },
|
||
spec: {
|
||
content: {
|
||
html: content,
|
||
medium: moment_data,
|
||
raw: content
|
||
},
|
||
owner: "",
|
||
tags: tags,
|
||
visible: visible
|
||
}
|
||
};
|
||
|
||
if (loca && loca !== '数据拉取中..') {
|
||
pushData.metadata.annotations = { mylocal: loca };
|
||
}
|
||
|
||
cocoMessage.info("发布中..");
|
||
|
||
$.ajax({
|
||
type: "POST",
|
||
url: `/apis/${Theme.moments.push_api}/v1alpha1/moments`,
|
||
contentType: "application/json",
|
||
data: JSON.stringify(pushData),
|
||
success() {
|
||
cocoMessage.success('发布成功!');
|
||
location.reload();
|
||
},
|
||
error() {
|
||
cocoMessage.error('发布失败!');
|
||
release();
|
||
}
|
||
});
|
||
|
||
return;
|
||
}
|
||
|
||
if (act === 'update') {
|
||
|
||
let updateData = {
|
||
apiVersion: 'moment.halo.run/v1alpha1',
|
||
kind: 'Moment',
|
||
metadata: {
|
||
name: pid,
|
||
generateName: "moment-",
|
||
finalizers: ["tag-moment-protection", "moment-protection"],
|
||
version: parseInt($('.push_item').attr('version'))
|
||
},
|
||
spec: {
|
||
content: {
|
||
html: content,
|
||
medium: moment_data,
|
||
raw: content
|
||
},
|
||
owner: $('.push_item').attr('owner'),
|
||
releaseTime: $('.push_item').attr('releaseTime'),
|
||
tags: tags,
|
||
visible: visible
|
||
}
|
||
};
|
||
|
||
if (loca && loca !== '数据拉取中..') {
|
||
updateData.metadata.annotations = { mylocal: loca };
|
||
}
|
||
|
||
cocoMessage.info("更新中..");
|
||
|
||
$.ajax({
|
||
type: "PUT",
|
||
url: `/apis/${Theme.moments.api}/v1alpha1/moments/${pid}`,
|
||
contentType: "application/json",
|
||
data: JSON.stringify(updateData),
|
||
success() {
|
||
cocoMessage.success('更新成功!');
|
||
location.reload();
|
||
},
|
||
error() {
|
||
cocoMessage.error('更新失败!');
|
||
release();
|
||
}
|
||
});
|
||
}
|
||
});
|
||
|
||
//获取片刻类型参数
|
||
function get_moment_data(type) {
|
||
moment_data = [];
|
||
switch (type) {
|
||
case "image":
|
||
$(".t_media_item").each(function () {
|
||
var src = $(this).attr('data-src');
|
||
var type = $(this).attr('data-type');
|
||
var obj = {
|
||
url: src,
|
||
type: "PHOTO",
|
||
originType: type
|
||
}
|
||
moment_data.push(obj); //图片
|
||
});
|
||
break;
|
||
case "card":
|
||
$(".card_sortble .moment_card_item").each(function () {
|
||
var pid = $(this).attr('pid');
|
||
var type = $(this).attr('type');
|
||
var obj = {
|
||
url: pid,
|
||
type: "POST",
|
||
originType: type
|
||
}
|
||
moment_data.push(obj); //卡片
|
||
});
|
||
break;
|
||
case "audio":
|
||
get_audio_data();
|
||
break;
|
||
case "video":
|
||
get_video_data();
|
||
break;
|
||
}
|
||
}
|
||
|
||
//片刻音乐参数
|
||
function get_audio_data() {
|
||
var type = $('.audio_choose li.uk-active a').attr('au_type');
|
||
if (type == 'local') {
|
||
var url = $('input#moment_audio_url').val();
|
||
var obj = {
|
||
url: url,
|
||
type: "AUDIO",
|
||
originType: 'audio/' + type
|
||
}
|
||
} else {
|
||
var n_id = $('input#moment_audio_api').val();
|
||
var obj = {
|
||
url: n_id,
|
||
type: "AUDIO",
|
||
originType: 'audio/' + type
|
||
}
|
||
}
|
||
moment_data.push(obj);
|
||
}
|
||
|
||
//片刻视频参数
|
||
function get_video_data() {
|
||
var type = $('.video_choose li.uk-active a').attr('vi_type');
|
||
if (type == 'local') {
|
||
var url = $('input#moment_video_url').val();
|
||
var obj = {
|
||
url: url,
|
||
type: "VIDEO",
|
||
originType: 'video/mp4'
|
||
}
|
||
|
||
} else if (type == 'bili') {
|
||
var bvid = $('input#moment_video_bili').val();
|
||
var obj = {
|
||
url: bvid,
|
||
type: "VIDEO",
|
||
originType: 'video/bili'
|
||
}
|
||
}
|
||
moment_data.push(obj);
|
||
|
||
}
|
||
|
||
//片刻空值提示
|
||
function get_moment_error(type) {
|
||
switch (type) {
|
||
case "card":
|
||
var v = $('.show_card .moment_card_item');
|
||
if (v.length == 0) {
|
||
return false;
|
||
}
|
||
break;
|
||
case "audio":
|
||
var au_type = $('.audio_choose li.uk-active a').attr('au_type');
|
||
var url = $('input#moment_audio_url').val(); //歌曲链接
|
||
var title = $('input#moment_audio_name').val(); //标题
|
||
var cover = $('.loacl_audio .audio_left img').length; //封面
|
||
if (au_type == 'local') {
|
||
if (url == '' || title == '' || cover == 0) {
|
||
return false;
|
||
}
|
||
} else {
|
||
var n_id = $('input#moment_audio_api').val();
|
||
if (n_id == '') {
|
||
return false;
|
||
}
|
||
}
|
||
break;
|
||
case "video":
|
||
var vi_type = $('.video_choose li.uk-active a').attr('vi_type');
|
||
var url = $('input#moment_video_url').val();
|
||
//var cover = $('.m_media_left img').length;
|
||
if (vi_type == 'local') {
|
||
if (url == '') {
|
||
return false;
|
||
}
|
||
} else {
|
||
var bvid = $('input#moment_video_bili').val();
|
||
if (bvid == '') {
|
||
return false;
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
|
||
// ajax 分类筛选 moment
|
||
$(document).on('click', '.moment_cat_nav ul li a', function () {
|
||
var $this = $(this);
|
||
if ($this.hasClass('disabled')) {
|
||
return false;
|
||
}
|
||
$('.moment_cat_nav ul li a').addClass('disabled');
|
||
|
||
var temp = $("#comment_form_reset");
|
||
var formHtml = $("#t_commentform").prop('outerHTML');
|
||
temp.html(formHtml);
|
||
|
||
$(".moment_list").empty();
|
||
$('#t_pagination a').hide();
|
||
$this.addClass('active').parent().siblings().children().removeClass('active');
|
||
|
||
var cat = $this.attr('data');
|
||
|
||
$.ajax({
|
||
type: "GET",
|
||
url: cat,
|
||
beforeSend: function () {
|
||
$('.moment_list').html('<div class="loading_box"><div uk-spinner></div></div>');
|
||
},
|
||
success: function (data) {
|
||
$('.moment_list .loading_box').remove();
|
||
var result = $(data).find(".moment_list .p_item");
|
||
$(".moment_list").append(result.fadeIn(300));
|
||
|
||
var $newPagination = $(data).find("#t_pagination");
|
||
var newHref = $newPagination.find("a").attr("data");
|
||
|
||
// 检查当前页面是否有分页容器,如果没有则补齐
|
||
if ($('#t_pagination').length === 0 && $newPagination.length > 0) {
|
||
$(".moment_list").after($newPagination.prop('outerHTML'));
|
||
}
|
||
|
||
var $paginationBtn = $('#t_pagination a');
|
||
|
||
if (newHref === undefined) {
|
||
$paginationBtn.hide();
|
||
} else {
|
||
$paginationBtn.attr("data", newHref).text(Theme.site_page).show();
|
||
$('#t_pagination').show();
|
||
}
|
||
getMomentAudio();
|
||
initAgree();
|
||
if (typeof lazyLoadInstance !== 'undefined') lazyLoadInstance.update();
|
||
$('.moment_cat_nav ul li a').removeClass('disabled');
|
||
initializeMomentFold();
|
||
// if (typeof modify_moment_video_size === 'function') modify_moment_video_size();
|
||
if (cat.indexOf('tag=') !== -1) {
|
||
history.pushState({ url: cat }, '', cat);
|
||
} else {
|
||
history.pushState({ url: cat }, '', '/');
|
||
}
|
||
document.cookie = "page=; path=/; domain=anian.cc; max-age=0";
|
||
}
|
||
});
|
||
});
|
||
|
||
|
||
//ajax加载片刻
|
||
$(document).on('click', '#t_pagination a', function () {
|
||
const postListElement = document.getElementById("post_item");
|
||
var href = $(this).attr('data');
|
||
const currentPage = parseInt(href.match(/\d+/)[0]);
|
||
$.ajax({
|
||
type: "GET",
|
||
url: href,
|
||
beforeSend: function () {
|
||
$('#t_pagination .post-paging').html('<div uk-spinner></div>');
|
||
},
|
||
success: function (posts) {
|
||
|
||
if (posts) {
|
||
|
||
var result = $(posts).find(".moment_list .p_item");
|
||
$('#t_pagination .post-paging').html(`<a>${Theme.site_page}</a>`);
|
||
$(".moment_list").append(result.fadeIn(300));
|
||
window.pjax && window.pjax.refresh(postListElement)
|
||
var newhref = $(posts).find("#t_pagination a").attr("data"); //找出新的下一页链接
|
||
|
||
if (newhref != undefined) {
|
||
$("#t_pagination a").attr("data", newhref);
|
||
$('#t_pagination a').show();
|
||
} else {
|
||
$("#t_pagination a").hide(); //如果没有下一页了,隐藏
|
||
}
|
||
|
||
$body.animate({ scrollTop: result.offset().top - 58 }, 500);
|
||
getMomentAudio();
|
||
initAgree();
|
||
|
||
lazyLoadInstance.update();
|
||
initializeMomentFold();
|
||
// modify_moment_video_size();
|
||
document.cookie = `page=${encodeURIComponent(currentPage)}; path=/; domain=anian.cc`;
|
||
} else {
|
||
$('#t_pagination a').hide();
|
||
}
|
||
|
||
|
||
}
|
||
});
|
||
return false;
|
||
|
||
});
|
||
|
||
|
||
// 图库分类切换 AJAX (完整版)
|
||
$(document).ready(function () {
|
||
// 1. 先解绑旧事件,防止重复绑定导致的冲突
|
||
$(document).off('click', '#cat_nav_items a.cat-link');
|
||
|
||
// 2. 绑定新的点击事件
|
||
$(document).on('click', '#cat_nav_items a.cat-link', function (e) {
|
||
// 阻止默认行为
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.stopImmediatePropagation();
|
||
|
||
var $this = $(this);
|
||
|
||
// 3. 状态检查
|
||
if ($this.hasClass('disabled') || $this.hasClass('active')) {
|
||
return false;
|
||
}
|
||
|
||
// 获取 AJAX 请求地址 (用于后端获取数据)
|
||
var url = $this.data('href');
|
||
if (!url) {
|
||
console.error('未找到分类链接地址');
|
||
return false;
|
||
}
|
||
|
||
// --- 【新增逻辑 1】准备要显示在浏览器地址栏的 URL ---
|
||
// 获取链接的纯文本内容(即中文分类名,如“苏州”)
|
||
// clone() 后移除 span 再取 text,防止“全部”后面的空格干扰
|
||
var tagText = $this.clone().find('span').remove().end().text().trim();
|
||
|
||
var displayUrl;
|
||
if (tagText === '全部') {
|
||
displayUrl = '/photos';
|
||
} else {
|
||
// 使用 encodeURIComponent 处理中文,防止 URL 乱码
|
||
displayUrl = '/photos?tag=' + encodeURIComponent(tagText);
|
||
}
|
||
// ----------------------------------------------------
|
||
|
||
// 4. UI 状态更新
|
||
$('#cat_nav_items a').addClass('disabled');
|
||
$this.addClass('active')
|
||
.parent()
|
||
.siblings()
|
||
.children('a')
|
||
.removeClass('active');
|
||
|
||
// 5. 发起 AJAX 请求
|
||
$.ajax({
|
||
type: "GET",
|
||
url: url,
|
||
beforeSend: function () {
|
||
$("#photos_item").html(
|
||
'<div class="loading_box" style="text-align:center;padding:50px;"><div uk-spinner></div></div>'
|
||
);
|
||
$('#p_pagination').hide();
|
||
},
|
||
success: function (data) {
|
||
var $data = $(data);
|
||
|
||
// 6. 替换相册列表内容
|
||
var newContent = $data.find("#photos_item").html();
|
||
$("#photos_item").html(newContent);
|
||
|
||
// 7. 同步更新分页区域
|
||
var $newPagination = $data.find("#p_pagination");
|
||
if ($newPagination.length > 0) {
|
||
var newHref = $newPagination.find("a").attr("data");
|
||
if (newHref) {
|
||
if ($('#p_pagination').length === 0) {
|
||
$("#photos_item").after($newPagination.prop('outerHTML'));
|
||
} else {
|
||
$('#p_pagination').replaceWith($newPagination.prop('outerHTML'));
|
||
}
|
||
$('#p_pagination').show();
|
||
} else {
|
||
$('#p_pagination').hide();
|
||
}
|
||
} else {
|
||
$('#p_pagination').hide();
|
||
}
|
||
|
||
// 8. 重新初始化插件
|
||
if (typeof pix !== 'undefined' && pix.initGalleryPhotos) {
|
||
pix.initGalleryPhotos();
|
||
}
|
||
if ($('.gallery-photos').length > 0 && typeof waterfall === 'function') {
|
||
waterfall('.gallery-photos');
|
||
}
|
||
|
||
// 9. 恢复点击状态
|
||
$('#cat_nav_items a').removeClass('disabled');
|
||
|
||
// --- 【新增逻辑 2】修改浏览器 URL ---
|
||
// 使用 pushState 更新地址栏,不刷新页面
|
||
// 参数:state对象, 标题, 新URL
|
||
history.pushState({ path: displayUrl }, '', displayUrl);
|
||
// ----------------------------------
|
||
|
||
// 10. 清理分页 Cookie
|
||
document.cookie = "page=; path=/; domain=anian.cc; max-age=0";
|
||
},
|
||
error: function () {
|
||
$('#cat_nav_items a').removeClass('disabled');
|
||
cocoMessage.error('内容获取失败');
|
||
$("#photos_item").empty();
|
||
}
|
||
});
|
||
|
||
return false;
|
||
});
|
||
});
|
||
|
||
|
||
//ajax加载图库
|
||
$(document).on('click', '#p_pagination a', function () {
|
||
var href = $(this).attr('data');
|
||
const currentPage = parseInt(href.match(/\d+/)[0]);
|
||
$.ajax({
|
||
type: "GET",
|
||
url: href,
|
||
beforeSend: function () {
|
||
$('#p_pagination .post-paging').html('<div uk-spinner></div>');
|
||
},
|
||
success: function (photos) {
|
||
if (photos) {
|
||
var result = $(photos).find(".norpost_list .gallery-photo");
|
||
$('#p_pagination .post-paging').html(`<a>${Theme.site_page}</a>`);
|
||
$(".gallery-photos").append(result.fadeIn(300));
|
||
|
||
var newhref = $(photos).find("#p_pagination a").attr("data"); //找出新的下一页链接
|
||
|
||
if (newhref != undefined) {
|
||
$("#p_pagination a").attr("data", newhref);
|
||
$('#p_pagination a').show();
|
||
} else {
|
||
$("#p_pagination a").hide(); //如果没有下一页了,隐藏
|
||
}
|
||
pix.initGalleryPhotos();
|
||
document.cookie = `page=${encodeURIComponent(currentPage)}; path=/; domain=anian.cc`;
|
||
} else {
|
||
$('#p_pagination a').hide();
|
||
}
|
||
}
|
||
});
|
||
return false;
|
||
|
||
});
|
||
|
||
//阅读更多按钮
|
||
$(document).on('click', 'a.show-more-btn', function () {
|
||
var t = $(this);
|
||
t.prev().show();
|
||
t.next().show();
|
||
t.siblings('.dotd').hide();
|
||
t.hide();
|
||
});
|
||
|
||
$(document).on('click', 'a.read-less-btn', function () {
|
||
var t = $(this);
|
||
t.siblings('.rm_hidden').hide();
|
||
t.siblings('.dotd').show();
|
||
t.prev().show();
|
||
t.hide();
|
||
});
|
||
|
||
|
||
//ajax加载评论
|
||
$(document).on('click', '.show_comment', function () {
|
||
$('.blog_list_inner').css('min-height', 'calc(100vh)');
|
||
var pid = $(this).attr('pid');
|
||
var other = $(this).parents('.moment_item').siblings('div');
|
||
$.each(other, function (name, value) {
|
||
|
||
//遍历每个 回复表单
|
||
var otherid = $(this).find('.show_comment').attr('pid');
|
||
$("#halo-comment-" + otherid).hide();
|
||
|
||
});
|
||
$(`#halo-comment-${pid}`).css('display', $(`#halo-comment-${pid}`).css('display') == 'block' ? 'none' : 'block');
|
||
|
||
});
|
||
|
||
//片刻点赞
|
||
$(document).on('click', '.up_like ', function () {
|
||
|
||
if ($(this).hasClass('done')) {
|
||
cocoMessage.info("地久天长");
|
||
return false;
|
||
} else {
|
||
$(this).addClass('done');
|
||
var pid = $(this).data("id");
|
||
var key = $(this).data("key");
|
||
// console.log(key)
|
||
let agreeArr = localStorage.getItem(`pix.upvoted.${key}.names`)
|
||
? JSON.parse(localStorage.getItem(`pix.upvoted.${key}.names`))
|
||
: [];
|
||
rateHolder = $(this).children('span');
|
||
iconHolder = $(this).children('i');
|
||
$.ajax({
|
||
type: 'post',
|
||
contentType: "application/json; charset=utf-8",
|
||
url: '/apis/api.halo.run/v1alpha1/trackers/upvote',
|
||
data: JSON.stringify({
|
||
group: key == "moment" ? "moment.halo.run" : "content.halo.run",
|
||
plural: key == "moment" ? "moments" : "posts",
|
||
name: pid,
|
||
}),
|
||
success: function (data) {
|
||
$(iconHolder).toggleClass('ri-heart-2-fill');
|
||
var num = $(rateHolder).text();
|
||
$(rateHolder).text(++num);
|
||
agreeArr.push(pid);
|
||
const val = JSON.stringify(agreeArr);
|
||
localStorage.setItem(`pix.upvoted.${key}.names`, val);
|
||
cocoMessage.success("卿卿与黄");
|
||
}
|
||
}); // end ajax
|
||
|
||
}
|
||
});
|
||
|
||
function initAgree() {
|
||
var agreeAnnius = $('.up_like')
|
||
if (agreeAnnius.length > 0) {
|
||
let agreeArr = JSON.parse(localStorage.getItem(`pix.upvoted.${$(agreeAnnius[0]).data("key")}.names`))
|
||
for (var i = 0; i < agreeAnnius.length; i++) {
|
||
let pid = $(agreeAnnius[i]).attr('data-id');
|
||
if (agreeArr != null) {
|
||
let flag = agreeArr.includes(pid);
|
||
if (flag) {
|
||
$(agreeAnnius[i]).addClass('done');
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
function getMomentAudio() {
|
||
var audioList = $('.pix_player.qt')
|
||
if (audioList.length > 0) {
|
||
for (var i = 0; i < audioList.length; i++) {
|
||
let id = $(audioList[i]).attr('id');
|
||
let type = $(audioList[i]).attr('type');
|
||
var result = type.substring(type.indexOf("audio/") + 6);
|
||
if (id != null && id != '') {
|
||
var api = `${Theme.play.pix_mu_api || 'https://api.i-meto.com/meting/api'}?type=song&id=:id`
|
||
var meta = {
|
||
type: result,
|
||
id: id,
|
||
}
|
||
let url = api.replace(":id", meta.id);
|
||
$.ajax({
|
||
type: "get",
|
||
url: url,
|
||
success: function (res) {
|
||
var html = ''
|
||
if (res.length > 0) {
|
||
let author = res[0].author;
|
||
let pic = res[0].pic;
|
||
let title = res[0].title;
|
||
let url = res[0].url;
|
||
let lrc = res[0].lrc;
|
||
html = `<div class="player_thum">
|
||
<img src="${pic}">
|
||
</div>
|
||
<div class="player_meta">
|
||
<div class="title"><span class="name">${title}</span><span class="author">${author}</span></div>
|
||
<div class="player_tool">
|
||
<div class="player_time"><div class="current_time"></div><span></span><div class="total_time"></div></div>
|
||
</div>
|
||
</div>
|
||
<a class="play_btn" data ="${url}" lrc="${lrc}"><i class="ri-play-line"></i></a>
|
||
<div class="play_bg"><img src="${pic}"></div>`;
|
||
} else {
|
||
html = '音乐参数错误';
|
||
}
|
||
$('#' + id).html(html);
|
||
|
||
}
|
||
});
|
||
|
||
}
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
// 初始化:解析URL的tag参数,匹配对应分类(中文名称)并触发原有请求
|
||
function initTagSwitch() {
|
||
const pathname = window.location.pathname;
|
||
const urlParams = new URLSearchParams(window.location.search);
|
||
const activeTag = urlParams.get('tag');
|
||
|
||
// 如果没有 tag 参数,直接退出
|
||
if (!activeTag || activeTag.trim() === '') {
|
||
return;
|
||
}
|
||
|
||
let targetLink = $(); // 初始化空 jQuery 对象
|
||
|
||
// --- 1. 判断是否为 Posts (文章归档) 页面 ---
|
||
if (pathname === '/archives') {
|
||
targetLink = $('.posts_cat_nav ul li a').filter(function () {
|
||
// 保持你原有的 Post 文本提取逻辑 (过滤文本节点)
|
||
const linkText = $(this).contents().filter(function () {
|
||
return this.nodeType === 3;
|
||
}).text().trim();
|
||
return linkText === activeTag;
|
||
});
|
||
}
|
||
|
||
// --- 2. 判断是否为 Photos (相册) 页面 ---
|
||
else if (pathname === '/photos') {
|
||
targetLink = $('#cat_nav_items a.cat-link').filter(function () {
|
||
// 使用针对相册 HTML 结构的文本提取逻辑 (移除 span 干扰)
|
||
const linkText = $(this).clone().find('span').remove().end().text().trim();
|
||
return linkText === activeTag;
|
||
});
|
||
}
|
||
|
||
// --- 3. 如果找到了匹配的链接,触发点击 ---
|
||
if (targetLink.length > 0) {
|
||
// 确保 DOM 完全就绪后再点击,加个小延迟防止插件未绑定
|
||
setTimeout(function () {
|
||
targetLink.click();
|
||
}, 50);
|
||
}
|
||
}
|
||
|
||
// ajax分类筛选 posts(完全保留原有请求逻辑,仅新增tag参数URL同步)
|
||
$(document).on('click', '.posts_cat_nav ul li a', function (e) {
|
||
e.preventDefault();
|
||
const postListElement = document.getElementById("post_item");
|
||
var t = $('.posts_cat_nav ul li a');
|
||
|
||
if (t.hasClass('disabled')) {
|
||
return false;
|
||
}
|
||
$('.posts_cat_nav ul li a').addClass('disabled');
|
||
|
||
$(".norpost_list").empty();
|
||
$('#pagination a').hide();
|
||
$(this).addClass('active');
|
||
$(this).parent().siblings().children().removeClass('active');
|
||
|
||
var cat = $(this).attr('data');
|
||
// 替换:获取a标签内的中文文本并去除空格
|
||
var tag = $(this).text().trim();
|
||
|
||
$.ajax({
|
||
type: "GET",
|
||
url: cat, // 完全保留原有请求URL,不修改
|
||
headers: {
|
||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
|
||
},
|
||
beforeSend: function () {
|
||
$('.norpost_list').html('<div class="loading_box"><div uk-spinner></div></div>');
|
||
},
|
||
success: function (data) {
|
||
$('#pagination a').text(Theme.site_page);
|
||
var result = $(data).find(".norpost_list").children();
|
||
$(".norpost_list").append(result.fadeIn(300));
|
||
window.pjax && window.pjax.refresh(postListElement);
|
||
|
||
let newhref = $(data).find("#pagination a").attr("data") || $(data).find(".arc_pagenav a").attr("data");
|
||
if (newhref != undefined) {
|
||
$("#pagination a").attr("data", newhref);
|
||
$('#pagination a').show();
|
||
} else {
|
||
$('#pagination a').hide();
|
||
}
|
||
|
||
$('.loading_box').remove();
|
||
initAgree();
|
||
lazyLoadInstance.update();
|
||
$('.posts_cat_nav ul li a').removeClass('disabled');
|
||
|
||
// 仅新增:基于中文tag构造URL并更新(不影响请求逻辑)
|
||
const urlParams = new URLSearchParams();
|
||
let newUrl = '/archives';
|
||
// 替换:判断是否为"全部",非全部则追加中文tag参数
|
||
if (tag !== '全部' && tag !== '') {
|
||
urlParams.append('tag', tag);
|
||
newUrl = `${newUrl}?${urlParams.toString()}`;
|
||
}
|
||
history.pushState({ url: newUrl }, '', newUrl);
|
||
document.cookie = "page=; path=/; domain=anian.cc; max-age=0";
|
||
},
|
||
error: function () {
|
||
$('.posts_cat_nav ul li a').removeClass('disabled');
|
||
}
|
||
});
|
||
});
|
||
|
||
//首页ajax加载文章
|
||
$('body').on('click', '#pagination a', function () {
|
||
const postListElement = document.getElementById("post_item");
|
||
var href = $(this).attr('data');
|
||
const currentPage = parseInt(href.match(/\d+/)[0]);
|
||
$.ajax({
|
||
type: "GET",
|
||
url: href,
|
||
headers: {
|
||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
|
||
},
|
||
beforeSend: function () {
|
||
$('#pagination .post-paging').html('<div uk-spinner></div>');
|
||
},
|
||
success: function (data) {
|
||
if (data) {
|
||
var result = $(data).find(".norpost_list ").children();
|
||
$('#pagination .post-paging').html(`<a>${Theme.site_page}</a>`);
|
||
$('.norpost_list').append($(result).fadeIn(400));
|
||
|
||
window.pjax && window.pjax.refresh(postListElement)
|
||
|
||
var newhref = $(data).find("#pagination a").attr("data") || $(data).find(".arc_pagenav a").attr("data"); //找出新的下一页链接
|
||
|
||
if (newhref != undefined) {
|
||
$("#pagination a").attr("data", newhref);
|
||
$('#pagination a').show();
|
||
} else {
|
||
$("#pagination a").hide(); //如果没有下一页了,隐藏
|
||
}
|
||
$body.animate({ scrollTop: result.offset().top - 58 }, 500);
|
||
initAgree()
|
||
lazyLoadInstance.update();
|
||
document.cookie = `page=${encodeURIComponent(currentPage)}; path=/; domain=anian.cc`;
|
||
}
|
||
|
||
}
|
||
});
|
||
return false;
|
||
});
|
||
|
||
//分类页面文章加载
|
||
$('body').on('click', '.arc_pagenav a', function () {
|
||
const postListElement = document.getElementById("post_item");
|
||
$(this).hide();
|
||
var content = $('.norpost_list');
|
||
var href = $(this).attr('data');
|
||
if (href != undefined) {
|
||
$.ajax({
|
||
type: "GET",
|
||
url: href,
|
||
headers: {
|
||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
|
||
},
|
||
beforeSend: function () {
|
||
$('.arc_pagenav').append('<div uk-spinner></div>');
|
||
},
|
||
success: function (data) {
|
||
var post = $(data).find(".norpost_list").children();
|
||
content.append(post.fadeIn(300));
|
||
|
||
window.pjax && window.pjax.refresh(postListElement)
|
||
|
||
var newhref = $(data).find(".arc_pagenav a").attr("data"); //找出新的下一页链接
|
||
if (newhref != undefined) {
|
||
$(".arc_pagenav a").attr("data", newhref);
|
||
$('.arc_pagenav a').show();
|
||
} else {
|
||
$(".arc_pagenav a").hide(); //如果没有下一页了,隐藏
|
||
}
|
||
|
||
$('.arc_pagenav .uk-spinner').remove();
|
||
|
||
$body.animate({ scrollTop: post.offset().top - 58 }, 500);
|
||
initAgree()
|
||
lazyLoadInstance.update();
|
||
}
|
||
});
|
||
}
|
||
|
||
return false;
|
||
|
||
});
|
||
|
||
function loginUrl() {
|
||
window.location.href = `/login?redirect_uri=${encodeURIComponent(window.location.pathname)}`;
|
||
}
|
||
|
||
$(document).on('mouseenter', '.lbc .left_menu_box ul li a , body.mod_third_s .left_menu_box ul li a', function (event) {
|
||
var title = $(this).find('.nav_title').text();
|
||
$(this).append("<span class='menu_tips'>" + title + "</span>");
|
||
});
|
||
|
||
$(document).on('mouseleave', '.lbc .left_menu_box ul li a , body.mod_third_s .left_menu_box ul li a', function (event) {
|
||
$(this).find('.menu_tips').remove();
|
||
|
||
});
|
||
|
||
//滚动
|
||
$(document).ready(function (e) {
|
||
$(window).scroll(function () {
|
||
|
||
var b = $(window).scrollTop(); //监控窗口已滚动的距离;
|
||
|
||
if (b > 190) {
|
||
|
||
$('.top_bar').addClass('mobile_active');
|
||
|
||
} else {
|
||
$('.top_bar').removeClass('mobile_active');
|
||
}
|
||
|
||
if (b > 200) {
|
||
$('a.go_top').addClass('show');
|
||
} else {
|
||
$('a.go_top').removeClass('show');
|
||
}
|
||
|
||
});
|
||
});
|
||
|
||
$.fn.autoTextarea = function (options) {
|
||
var defaults = {
|
||
maxHeight: null,//文本框是否自动撑高,默认:null,不自动撑高;如果自动撑高必须输入数值,该值作为文本框自动撑高的最大高度
|
||
minHeight: 50
|
||
};
|
||
var opts = $.extend({}, defaults, options);
|
||
return $(this).each(function () {
|
||
$(this).bind("paste cut keydown keyup focus blur", function () {
|
||
var height, style = this.style;
|
||
this.style.height = opts.minHeight + 'px';
|
||
if (this.scrollHeight > opts.minHeight) {
|
||
if (opts.maxHeight && this.scrollHeight > opts.maxHeight) {
|
||
height = opts.maxHeight;
|
||
style.overflowY = 'scroll';
|
||
} else {
|
||
height = this.scrollHeight;
|
||
style.overflowY = 'hidden';
|
||
}
|
||
style.height = height + 'px';
|
||
}
|
||
});
|
||
});
|
||
};
|
||
|
||
$('body').on('click', '.com_msg_btn', function () {
|
||
|
||
var num = $(this).attr('check');
|
||
if (num == 0) {
|
||
return false;
|
||
}
|
||
$.ajax({
|
||
type: 'POST',
|
||
dataType: 'json',
|
||
url: Theme.ajaxurl,
|
||
data: {
|
||
'action': 'up_unread_msg',
|
||
},
|
||
beforeSend: function () {
|
||
|
||
},
|
||
success: function (data) {
|
||
if (data.code == '0') {
|
||
$('small.f_unread_num').remove();
|
||
} else {
|
||
return false;
|
||
}
|
||
}
|
||
});
|
||
|
||
});
|
||
|
||
//搜索类型
|
||
$('body').on('click', '.s_set_box a', function () {
|
||
var type = $(this).attr('data');
|
||
$(this).addClass('active').siblings('a').removeClass('active');
|
||
$('form#index_search input[type="hidden"]').val(type);
|
||
$.cookie('s_type', type, { expires: 30, path: '/', domain: 'anian.cc' });
|
||
});
|
||
|
||
$('body').on('click', '.top_s_box a', function () {
|
||
UIkit.dropdown('.s_set_box').hide(false);
|
||
var data = $(this).attr('data');
|
||
var type = $(this).text();
|
||
$('.set_text').text(type);
|
||
$('form#top_search input[type="hidden"]').val(data);
|
||
});
|
||
|
||
//黑暗模式
|
||
$('body').on('click', '.t_dark a', function () {
|
||
var date = new Date();
|
||
date.setTime(date.getTime() + (3 * 60 * 60 * 1000));
|
||
var t = $('html');
|
||
if (t.hasClass('dark')) {
|
||
document.cookie = "dark=normal;path=/;domain=anian.cc;expires=" + date.toGMTString();
|
||
} else {
|
||
document.cookie = "dark=dark;path=/;domain=anian.cc;expires=" + date.toGMTString();
|
||
}
|
||
t.toggleClass('dark');
|
||
|
||
});
|
||
//片刻管理按钮
|
||
|
||
$(document).on('mouseenter', '.post_control_btn', function (event) {
|
||
var a = $(this).siblings('.post_control_box');
|
||
a.addClass('show');
|
||
});
|
||
|
||
$(document).on('mouseleave', '.post_control', function (event) {
|
||
$(this).find('.post_control_box').removeClass('show');
|
||
});
|
||
|
||
|
||
//社交小工具二维码
|
||
$(document).on('mouseenter', '.sw_social', function (event) {
|
||
var qrbox = $(this).siblings('.sw_qrcode');
|
||
if (qrbox.length > 0) {
|
||
qrbox.addClass('active');
|
||
qrbox.fadeIn(200);
|
||
}
|
||
});
|
||
|
||
$(document).on('mouseleave', '.sw_social', function (event) {
|
||
var qrbox = $(this).siblings('.sw_qrcode');
|
||
if (qrbox.length > 0) {
|
||
qrbox.removeClass('active');
|
||
qrbox.fadeOut(200);
|
||
}
|
||
});
|
||
|
||
//点击收起移动侧栏
|
||
$('body').on('click', '.m_offcanvas', function () {
|
||
var target = event.target;
|
||
var parentAnchor = $(target).closest('a');
|
||
if (target.getAttribute('href') == '#' || parentAnchor.attr('href') == '#') {
|
||
} else {
|
||
UIkit.offcanvas('.m_offcanvas').hide();
|
||
}
|
||
});
|
||
|
||
// 刷新内容(兼容一言和今日诗词API)
|
||
$('body').on('click', '.yiyan_box .change', function () {
|
||
var url = Theme.widget_yiyan.api || 'https://v1.hitokoto.cn';
|
||
fetch(url)
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
const targetElement = document.querySelector('.yiyan_box p');
|
||
if (url.includes('jinrishici.com')) {
|
||
// 今日诗词API处理逻辑:标题添加《》
|
||
targetElement.innerText = data.content;
|
||
targetElement.setAttribute("uk-tooltip", `《${data.origin}》${data.author}`);
|
||
} else {
|
||
// 原有一言API处理逻辑
|
||
targetElement.innerText = data.hitokoto;
|
||
targetElement.setAttribute("uk-tooltip", data.from);
|
||
}
|
||
})
|
||
.catch(console.error);
|
||
});
|
||
|
||
$('.yiyan_box .change').click();
|
||
|
||
//pjax
|
||
if (Theme.pjax) {
|
||
let pjaxSelectors = ["head title", "#pjax-container", ".pjax"]
|
||
var pjax = new Pjax({
|
||
elements: 'a:not([target="_blank"]):not([pjax="exclude"])',
|
||
selectors: pjaxSelectors,
|
||
analytics: false,
|
||
cacheBust: false,
|
||
});
|
||
|
||
document.addEventListener('pjax:send', function () {
|
||
NProgress.start();
|
||
})
|
||
|
||
document.addEventListener('pjax:complete', function () {
|
||
lazyLoadInstance.update();
|
||
typeof hljs === 'object' && hljs.highlightAll();
|
||
typeof Prism === 'object' && Prism.highlightAll();
|
||
autoload_posts_music();
|
||
initBlog();
|
||
refreshCommentWidget();
|
||
NProgress.done();
|
||
document.cookie = "page=; path=/; domain=anian.cc; max-age=0";
|
||
})
|
||
}
|
||
|
||
// 刷新评论组件函数
|
||
function refreshCommentWidget() {
|
||
const commentWrappers = document.querySelectorAll('.halo-comment');
|
||
if (commentWrappers.length > 0) {
|
||
commentWrappers.forEach(wrapper => {
|
||
const scripts = wrapper.querySelectorAll('script[type="module"]');
|
||
scripts.forEach(oldScript => {
|
||
const newScript = document.createElement('script');
|
||
newScript.type = 'module';
|
||
// 复制所有属性
|
||
Array.from(oldScript.attributes).forEach(attr => {
|
||
if (attr.name !== 'type') {
|
||
newScript.setAttribute(attr.name, attr.value);
|
||
}
|
||
});
|
||
// 复制脚本内容
|
||
newScript.textContent = oldScript.textContent;
|
||
// 替换旧脚本
|
||
oldScript.parentNode.insertBefore(newScript, oldScript);
|
||
oldScript.remove();
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
$('body').on('click', '.msg_modal_inner .unread_box .box .mark_read', function (e) {
|
||
// console.log(e)
|
||
let msg_name = $(this).parent()[0].getAttribute('msg-name')
|
||
let username = Theme.username
|
||
$.ajax({
|
||
type: "put",
|
||
url: `/apis/api.notification.halo.run/v1alpha1/userspaces/${username}/notifications/${msg_name}/mark-as-read`,
|
||
success: function (res) {
|
||
pix.getMsg()
|
||
}
|
||
});
|
||
})
|
||
|
||
|
||
const getWindowInfo = () => {
|
||
pix.initTopBar()
|
||
};
|
||
const debounce = (fn, delay) => {
|
||
let timer;
|
||
return function () {
|
||
if (timer) {
|
||
clearTimeout(timer);
|
||
}
|
||
timer = setTimeout(() => {
|
||
fn();
|
||
}, delay);
|
||
}
|
||
};
|
||
|
||
const cancalDebounce = debounce(getWindowInfo, 1);
|
||
window.addEventListener('resize', cancalDebounce);
|
||
|
||
//固定顶部栏
|
||
$(document).scroll(function () {
|
||
let topBar = $('#masthead .top_bar');
|
||
var placeholder = document.querySelector('#masthead .uk-sticky-placeholder');
|
||
var width = topBar.width();
|
||
var scrT = document.documentElement.scrollTop;
|
||
if (window.innerWidth > 960) {
|
||
// 如果滚动的距离>60
|
||
if (scrT > 60) {
|
||
topBar.addClass('uk-active uk-sticky-fixed').css({ "width": width, "top": '0px', "position": "fixed" });
|
||
placeholder.hidden = false;
|
||
} else {
|
||
topBar.removeClass('uk-active uk-sticky-fixed').css({ "width": "auto", "top": "auto", "position": "" });
|
||
placeholder.hidden = true;
|
||
}
|
||
} else {
|
||
// 如果滚动的距离>0
|
||
if (scrT > 0) {
|
||
topBar.addClass('uk-active uk-sticky-below')
|
||
} else {
|
||
topBar.removeClass('uk-active uk-sticky-below')
|
||
}
|
||
|
||
}
|
||
|
||
});
|
||
|
||
// 获取当前具有 "current" 类的元素
|
||
var currentElement = document.querySelector('.current');
|
||
|
||
// 检查是否找到了具有 "current" 类的元素
|
||
if (currentElement) {
|
||
// 将当前元素滚动到视图中
|
||
currentElement.scrollIntoView({
|
||
behavior: 'smooth', // 平滑滚动
|
||
block: 'start' // 将当前元素顶部对齐到视口顶部
|
||
});
|
||
}
|
||
|
||
$('body').on('click', '.listree-btn', function () {
|
||
"目录[+]" == $(".listree-btn").text() ? $(".listree-btn").attr("title", "收起").text("目录[-]").parent().next().show() : $(".listree-btn").attr("title", "展开").text("目录[+]").parent().next().hide();
|
||
return !1
|
||
});
|
||
|
||
// toc
|
||
function autotree() {
|
||
$(document).ready(function () {
|
||
$('.listree-titles').html('<a class="listree-btn" title="展开">目录[+]</a>')
|
||
$('#listree-ol').empty();
|
||
$("#listree-ol").css("display", "none")
|
||
|
||
// 获取所有标题元素
|
||
var headings = document.querySelectorAll('.post-single .single-content *:is(h1, h2, h3, h4, h5, h6)');
|
||
|
||
// 为标题元素添加 listree-list 类,并修改 id
|
||
headings.forEach(function (heading, index) {
|
||
heading.classList.add('listree-list');
|
||
heading.id = 'listree-list' + index;
|
||
});
|
||
|
||
// 创建一个空的目录列表
|
||
var tocList = document.querySelector('#listree-ol');
|
||
|
||
// 保存每个级别的父列表项
|
||
var parentItems = {};
|
||
|
||
// 遍历每个标题元素
|
||
headings.forEach(function (heading, index) {
|
||
// 创建列表项
|
||
var listItem = document.createElement('li');
|
||
|
||
// 创建标题链接
|
||
var link = document.createElement('a');
|
||
// 直接设置链接的href为标题元素的id
|
||
link.href = '#listree-list' + index;
|
||
link.classList.add('toc-link', 'node-name--' + heading.tagName);
|
||
link.textContent = heading.textContent.trim();
|
||
|
||
// 将标题链接添加到列表项中
|
||
listItem.appendChild(link);
|
||
|
||
// 获取当前标题级别
|
||
var level = parseInt(heading.tagName.slice(1));
|
||
|
||
// 查找当前标题的父级列表项
|
||
var parentItem = parentItems[level - 1];
|
||
|
||
// 如果存在父级列表项,则将当前列表项作为其子项
|
||
if (parentItem) {
|
||
// 如果父级列表项还没有子列表,则创建一个子列表
|
||
if (!parentItem.querySelector('ul')) {
|
||
var subList = document.createElement('ul');
|
||
parentItem.appendChild(subList);
|
||
}
|
||
|
||
// 将当前列表项添加到父级列表的子列表中
|
||
parentItem.querySelector('ul').appendChild(listItem);
|
||
} else {
|
||
// 如果不存在父级列表项,则将当前列表项直接添加到根列表中
|
||
tocList.appendChild(listItem);
|
||
}
|
||
|
||
// 更新当前级别的父列表项为当前列表项
|
||
parentItems[level] = listItem;
|
||
});
|
||
|
||
|
||
$(".listree-btn").click(function () {
|
||
"目录[+]" == $(".listree-btn").text() ? $(".listree-btn").attr("title", "收起").text("目录[-]").parent().next().show() : $(".listree-btn").attr("title", "展开").text("目录[+]").parent().next().hide();
|
||
return !1
|
||
});
|
||
$("a.toc-link").click(function (event) {
|
||
event.preventDefault();
|
||
var targetId = $(this).attr("href");
|
||
$("html, body").animate({
|
||
scrollTop: $(targetId).offset().top - 77
|
||
}, 800);
|
||
});
|
||
// 判断是否存在目录,设置显示或隐藏
|
||
if ($('#listree-ol').children().length > 0) {
|
||
$(".listree-box").css("display", "block");
|
||
} else {
|
||
$(".listree-box").css("display", "none");
|
||
}
|
||
})
|
||
jQuery(document).ready(function (f) {
|
||
var T = f(".listree-list");
|
||
if (T.length < 1)
|
||
return;
|
||
var b = [];
|
||
|
||
function Q() {
|
||
T.each(function () {
|
||
var T = f(this).offset();
|
||
b.push(Math.floor(T.top))
|
||
})
|
||
}
|
||
|
||
function a(T) {
|
||
var b = f("#listree-ol li");
|
||
var Q = f(".listree-list dt");
|
||
if (b.length < 1)
|
||
return;
|
||
var a = b.outerHeight();
|
||
if (!b.eq(T).hasClass("current")) {
|
||
b.removeClass("current");
|
||
b.eq(T).addClass("current");
|
||
Q.animate({
|
||
top: a * T + (b.outerHeight() - Q.outerHeight()) / 2 + 1
|
||
}, 50)
|
||
}
|
||
}
|
||
|
||
function X() {
|
||
if ($('#listree-ol').children().length < 1)
|
||
return;
|
||
var f = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
|
||
var Q = Math.ceil(f + 77);
|
||
var X = 0;
|
||
for (var aU = 0; aU < b.length; aU++) {
|
||
if (Q >= b[aU]) {
|
||
X = aU
|
||
} else {
|
||
break
|
||
}
|
||
}
|
||
if (X < 0)
|
||
X = 0;
|
||
if (!T.eq(X).hasClass("current")) {
|
||
T.removeClass("current");
|
||
T.eq(X).addClass("current");
|
||
a(X)
|
||
}
|
||
}
|
||
|
||
Q();
|
||
setTimeout(X, 0);
|
||
f(window).on("scroll", X)
|
||
});
|
||
}
|
||
|
||
pix.addRuntime();
|
||
|
||
$(document).ready(function () {
|
||
$("[data-fancybox]").fancybox({
|
||
selector: '[data-fancybox]',
|
||
loop: true,
|
||
transitionEffect: 'slide',
|
||
protect: true,
|
||
buttons: ['slideShow', 'fullScreen', 'thumbs', 'close'],
|
||
hash: false
|
||
})
|
||
})
|
||
|
||
//菜单高亮
|
||
function highlightActiveMenu() {
|
||
let currentPath = window.location.pathname.replace(/\/+$/, "");
|
||
if (currentPath === "") currentPath = "/";
|
||
|
||
const menuLinks = document.querySelectorAll('a[href]:not([href^="javascript"])');
|
||
|
||
// 清除现有样式
|
||
menuLinks.forEach(link => {
|
||
link.style.color = "";
|
||
const icon = link.querySelector("i");
|
||
if (icon) icon.style.color = "";
|
||
});
|
||
|
||
// 高亮匹配项
|
||
menuLinks.forEach(link => {
|
||
let linkPath = link.getAttribute("href").replace(/\/+$/, "");
|
||
if (linkPath === "") linkPath = "/";
|
||
|
||
const isMatch =
|
||
currentPath === linkPath ||
|
||
(linkPath !== "/" && currentPath.startsWith(linkPath));
|
||
|
||
if (isMatch) {
|
||
link.style.color = "#4CAF50";
|
||
const icon = link.querySelector("i");
|
||
if (icon) icon.style.color = "#4CAF50";
|
||
}
|
||
});
|
||
}
|
||
|
||
// 指定日期黑白效果
|
||
function setPageGrayscale() {
|
||
const dateList = ['12-13'];
|
||
const style = document.createElement('style');
|
||
style.innerHTML = '.grayscale-mode{filter:grayscale(100%)!important;-webkit-filter:grayscale(100%)!important;transition:filter 60s ease!important;}';
|
||
document.head.appendChild(style);
|
||
const today = new Date();
|
||
const todayMd = `${today.getMonth() + 1}-${today.getDate()}`;
|
||
if (dateList.includes(todayMd)) {
|
||
document.documentElement.classList.add('grayscale-mode');
|
||
}
|
||
}
|
||
|
||
// 内容折叠初始化
|
||
function initializeMomentFold() {
|
||
const foldConfig = {
|
||
maxHeight: 240,
|
||
moreText: '展开',
|
||
lessText: '收起'
|
||
};
|
||
|
||
$('.moment-collapse-container').each(function () {
|
||
const $contentContainer = $(this);
|
||
if ($contentContainer.next('.moment-fold-btn').length > 0) return;
|
||
|
||
// 完整内容高度
|
||
const fullHeight = $contentContainer[0].scrollHeight;
|
||
const needFold = fullHeight > foldConfig.maxHeight;
|
||
if (!needFold) return;
|
||
|
||
// 初始化折叠状态
|
||
$contentContainer.addClass('collapsed').css('max-height', foldConfig.maxHeight + 'px');
|
||
const $foldBtn = $(`<button type="button" class="moment-fold-btn">${foldConfig.moreText}</button>`);
|
||
$contentContainer.after($foldBtn);
|
||
|
||
// 折叠/展开切换
|
||
$foldBtn.on('click', function () {
|
||
const isCollapsed = $contentContainer.hasClass('collapsed');
|
||
const heightDiff = fullHeight - foldConfig.maxHeight; // 完整高度与折叠高度的差值
|
||
|
||
if (isCollapsed) {
|
||
// 展开逻辑
|
||
$contentContainer.removeClass('collapsed').css('max-height', fullHeight + 'px');
|
||
$(this).text(foldConfig.lessText);
|
||
} else {
|
||
// 收起逻辑:页面向下滚动差值距离
|
||
$('html, body').animate({ scrollTop: $(window).scrollTop() - heightDiff }, 300, 'linear');
|
||
|
||
$contentContainer.addClass('collapsed').css('max-height', foldConfig.maxHeight + 'px');
|
||
$(this).text(foldConfig.moreText);
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
// 更换背景函数封装
|
||
function setFixedBackground(bgImageUrl) {
|
||
const body = document.body;
|
||
body.classList.add('common-fixed-bg');
|
||
body.style.backgroundImage = `url('${bgImageUrl}')`;
|
||
}
|
||
|
||
// 更换banner函数封装(PJAX触发)
|
||
const bg1 = document.querySelector('.bg1');
|
||
const bg2 = document.querySelector('.bg2');
|
||
let bannerIndex = 0;
|
||
let isBg1Active = true;
|
||
let hasSingleBannerShown = false;
|
||
|
||
let bannerImages = [];
|
||
|
||
function preloadImage(url) {
|
||
return new Promise((resolve, reject) => {
|
||
const img = new Image();
|
||
img.onload = () => resolve(url);
|
||
img.onerror = reject;
|
||
img.src = url;
|
||
});
|
||
}
|
||
|
||
function changeBanner(url) {
|
||
const show = isBg1Active ? bg2 : bg1;
|
||
const hide = isBg1Active ? bg1 : bg2;
|
||
|
||
show.style.backgroundImage = `url(${url})`;
|
||
show.style.opacity = 1;
|
||
|
||
hide.style.opacity = 0;
|
||
|
||
isBg1Active = !isBg1Active;
|
||
}
|
||
|
||
async function safeChangeBanner(url) {
|
||
await preloadImage(url);
|
||
changeBanner(url);
|
||
}
|
||
|
||
function nextBanner() {
|
||
if (bannerImages.length < 1) return;
|
||
|
||
if (bannerImages.length === 1) {
|
||
// 第一次调用:显示图片并标记为已显示
|
||
if (!hasSingleBannerShown) {
|
||
safeChangeBanner(bannerImages[bannerIndex]);
|
||
hasSingleBannerShown = true;
|
||
}
|
||
// 非第一次调用:直接返回,不触发切换
|
||
return;
|
||
}
|
||
|
||
safeChangeBanner(bannerImages[bannerIndex]);
|
||
bannerIndex = (bannerIndex + 1) % bannerImages.length;
|
||
}
|
||
|
||
// 重置状态函数
|
||
function resetBannerState() {
|
||
bannerIndex = 0;
|
||
isBg1Active = true;
|
||
hasSingleBannerShown = false;
|
||
}
|
||
|
||
// 奇遇显示函数封装
|
||
function showCenterImage(imageUrl) {
|
||
const container = document.getElementById('centerImgContainer');
|
||
const img = document.getElementById('targetImg');
|
||
|
||
// 重置所有状态(避免上一次操作残留影响)
|
||
container.classList.remove('container-fade-active');
|
||
img.classList.remove('img-fade-in', 'img-fade-out');
|
||
img.style.opacity = 0;
|
||
img.src = ""; // 先清空原有src
|
||
|
||
// 定义图片加载成功的回调函数
|
||
function handleImageLoad() {
|
||
// 移除事件监听(防止重复绑定)
|
||
img.removeEventListener('load', handleImageLoad);
|
||
img.removeEventListener('error', handleImageError);
|
||
|
||
// 图片加载成功后,再执行淡入动画
|
||
container.classList.add('container-fade-active');
|
||
img.classList.add('img-fade-in');
|
||
|
||
// 图片显示1.5秒后,执行自动关闭逻辑
|
||
setTimeout(() => {
|
||
container.classList.remove('container-fade-active');
|
||
img.classList.add('img-fade-out');
|
||
|
||
setTimeout(() => {
|
||
img.classList.remove('img-fade-in', 'img-fade-out');
|
||
}, 500);
|
||
}, 1500);
|
||
}
|
||
|
||
// 定义图片加载失败的回调函数
|
||
function handleImageError() {
|
||
// 移除事件监听
|
||
img.removeEventListener('load', handleImageLoad);
|
||
img.removeEventListener('error', handleImageError);
|
||
|
||
// 重置容器和图片状态,不执行任何动画
|
||
container.classList.remove('container-fade-active');
|
||
img.classList.remove('img-fade-in', 'img-fade-out');
|
||
img.style.opacity = 0;
|
||
img.src = "";
|
||
}
|
||
|
||
// 绑定图片加载/失败事件监听(先绑定,再赋值src,避免缓存导致回调不触发)
|
||
img.addEventListener('load', handleImageLoad);
|
||
img.addEventListener('error', handleImageError);
|
||
|
||
// 最后赋值src,触发图片加载(异步操作)
|
||
img.src = imageUrl;
|
||
}
|
||
|
||
// 侧边栏农历信息显示函数
|
||
function anian_renderLunarUI(data) {
|
||
const textEl = document.getElementById('anianLunarText');
|
||
const defaultText = '一日不见如隔三秋';
|
||
|
||
if (!textEl) return;
|
||
if (!data) {
|
||
textEl.innerHTML = defaultText;
|
||
return;
|
||
}
|
||
|
||
const {
|
||
ganzhiYear = '',
|
||
lunarMonth = '',
|
||
lunarDay = '',
|
||
jieqi = '',
|
||
jijie = '',
|
||
traditionalFestival = ''
|
||
} = data;
|
||
|
||
let text = `${ganzhiYear}年${lunarMonth}${lunarDay}`;
|
||
|
||
const extra = [];
|
||
if (jieqi) extra.push(jieqi);
|
||
if (traditionalFestival) extra.push(traditionalFestival);
|
||
|
||
if (extra.length) {
|
||
text += `<br>${extra.join(' · ')}`;
|
||
}
|
||
|
||
textEl.innerHTML = text;
|
||
|
||
// 奇遇弹窗+背景图片设置
|
||
if (jieqi === '大寒') {
|
||
showCenterImage('/upload/qiyu-jieqi-dahan.png');
|
||
// setFixedBackground('/upload/2025-12-2.png');
|
||
}
|
||
|
||
switch (jijie) {
|
||
case "春季":
|
||
bannerImages.push('/upload/dingbu-chun.png');
|
||
break;
|
||
case "夏季":
|
||
bannerImages.push('/upload/dingbu-xia.png');
|
||
break;
|
||
case "秋季":
|
||
bannerImages.push('/upload/dingbu-qiu.png');
|
||
break;
|
||
case "冬季":
|
||
bannerImages.push('/upload/dingbu-dong.png');
|
||
break;
|
||
default:
|
||
bannerImages.push('/upload/dingbu-siji.png');
|
||
break;
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
}
|
||
|
||
// Cookie 是否存在
|
||
function anian_checkCookieExists(name) {
|
||
return document.cookie.includes(`${name}=`);
|
||
}
|
||
|
||
// 写入当日有效 Cookie(23:59 失效)
|
||
function anian_setDailyCookie(name, value) {
|
||
const now = new Date();
|
||
const china = new Date(now.getTime() + 8 * 3600 * 1000);
|
||
const expires = new Date(Date.UTC(
|
||
china.getUTCFullYear(),
|
||
china.getUTCMonth(),
|
||
china.getUTCDate(),
|
||
15, 59, 59
|
||
));
|
||
|
||
document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;domain=anian.cc`;
|
||
}
|
||
|
||
// 读取 Cookie
|
||
function anian_getCookieValue(name) {
|
||
const m = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
|
||
return m ? decodeURIComponent(m[2]) : null;
|
||
}
|
||
|
||
// 获取农历数据并触发渲染
|
||
function anian_handleLunarCookie() {
|
||
const apiUrl = 'https://cn.apihz.cn/api/time/getday.php?id=10011724&key=0bdd2d8b3d97c0d476c98a41f108a96f';
|
||
const cookieName = 'anian_lunar_info';
|
||
|
||
// 优先使用缓存
|
||
if (anian_checkCookieExists(cookieName)) {
|
||
try {
|
||
const data = JSON.parse(anian_getCookieValue(cookieName));
|
||
anian_renderLunarUI(data);
|
||
return;
|
||
} catch (_) { }
|
||
}
|
||
|
||
// 无缓存则请求 API
|
||
fetch(apiUrl)
|
||
.then(r => r.ok ? r.json() : Promise.reject())
|
||
.then(data => {
|
||
if (data.code !== 200) throw new Error();
|
||
|
||
const jieqi = (data.JIEQICN || '').includes('第1天') ? data.jieqi : '';
|
||
|
||
const lunarInfo = {
|
||
ganzhiYear: data.ganzhinian || '',
|
||
lunarMonth: data.nyue || '',
|
||
lunarDay: data.nri || '',
|
||
jieqi: jieqi || '',
|
||
jijie: data.jijie || '',
|
||
traditionalFestival: data.YIFESTIVAL || ''
|
||
};
|
||
|
||
anian_setDailyCookie(cookieName, JSON.stringify(lunarInfo));
|
||
anian_renderLunarUI(lunarInfo);
|
||
})
|
||
.catch(() => {
|
||
anian_renderLunarUI(null);
|
||
});
|
||
}
|
||
|
||
// 绿色数字时钟粒子效果
|
||
function initGreenDigitalClock() {
|
||
var t = 820;
|
||
var a = 250;
|
||
var r = 7;
|
||
var n = 10;
|
||
var e = .65;
|
||
var f;
|
||
var o = [];
|
||
|
||
const v = ["#00FF7F", "#32CD32", "#228B22", "#008000", "#006400", "#90EE90", "#98FB98", "#00FA9A", "#00FF00", "#3CB371"];
|
||
|
||
var h = [];
|
||
var u = [
|
||
[[0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0]],
|
||
[[0, 0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1]],
|
||
[[0, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1]],
|
||
[[1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 0]],
|
||
[[0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1]],
|
||
[[1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 0]],
|
||
[[0, 0, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 0]],
|
||
[[1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0]],
|
||
[[0, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 0]],
|
||
[[0, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0, 0]],
|
||
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
|
||
];
|
||
|
||
function l(t) {
|
||
var a = [];
|
||
f.fillStyle = "#006400";
|
||
var r = new Date;
|
||
var e = 70, o = 30;
|
||
var v = r.getHours();
|
||
var u = Math.floor(v / 10);
|
||
var l = v % 10;
|
||
a.push({ num: u });
|
||
a.push({ num: l });
|
||
a.push({ num: 10 });
|
||
var c = r.getMinutes();
|
||
var u = Math.floor(c / 10);
|
||
var l = c % 10;
|
||
a.push({ num: u });
|
||
a.push({ num: l });
|
||
a.push({ num: 10 });
|
||
var M = r.getSeconds();
|
||
var u = Math.floor(M / 10);
|
||
var l = M % 10;
|
||
a.push({ num: u });
|
||
a.push({ num: l });
|
||
for (var p = 0; p < a.length; p++) {
|
||
a[p].offsetX = e;
|
||
e = m(e, o, a[p].num, t);
|
||
if (p < a.length - 1) {
|
||
if (a[p].num != 10 && a[p + 1].num != 10) {
|
||
e += n
|
||
}
|
||
}
|
||
}
|
||
if (h.length == 0) {
|
||
h = a
|
||
} else {
|
||
for (var C = 0; C < h.length; C++) {
|
||
if (h[C].num != a[C].num) {
|
||
s(a[C]);
|
||
h[C].num = a[C].num
|
||
}
|
||
}
|
||
}
|
||
i(t);
|
||
g();
|
||
return r
|
||
}
|
||
|
||
function s(t) {
|
||
var a = t.num;
|
||
var n = u[a];
|
||
for (var e = 0; e < n.length; e++) {
|
||
for (var f = 0; f < n[e].length; f++) {
|
||
if (n[e][f] == 1) {
|
||
var h = {
|
||
offsetX: t.offsetX + r + r * 2 * f,
|
||
offsetY: 30 + r + r * 2 * e,
|
||
color: v[Math.floor(Math.random() * v.length)],
|
||
g: 1.5 + Math.random(),
|
||
vx: Math.pow(-1, Math.ceil(Math.random() * 10)) * 4 + Math.random(),
|
||
vy: -5
|
||
};
|
||
o.push(h)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
function i(t) {
|
||
for (var a = 0; a < o.length; a++) {
|
||
t.beginPath();
|
||
t.fillStyle = o[a].color;
|
||
t.arc(o[a].offsetX, o[a].offsetY, r, 0, 2 * Math.PI);
|
||
t.fill()
|
||
}
|
||
}
|
||
|
||
function g() {
|
||
var n = 0;
|
||
for (var f = 0; f < o.length; f++) {
|
||
var v = o[f];
|
||
v.offsetX += v.vx;
|
||
v.offsetY += v.vy;
|
||
v.vy += v.g;
|
||
if (v.offsetY > a - r) {
|
||
v.offsetY = a - r;
|
||
v.vy = -v.vy * e
|
||
}
|
||
if (v.offsetX > r && v.offsetX < t - r) {
|
||
o[n] = o[f];
|
||
n++
|
||
}
|
||
}
|
||
for (; n < o.length; n++) {
|
||
o.pop()
|
||
}
|
||
}
|
||
|
||
function m(t, a, n, e) {
|
||
var f = u[n];
|
||
for (var o = 0; o < f.length; o++) {
|
||
for (var v = 0; v < f[o].length; v++) {
|
||
if (f[o][v] == 1) {
|
||
e.beginPath();
|
||
e.arc(t + r + r * 2 * v, a + r + r * 2 * o, r, 0, 2 * Math.PI);
|
||
e.fill()
|
||
}
|
||
}
|
||
}
|
||
e.beginPath();
|
||
t += f[0].length * r * 2;
|
||
return t
|
||
}
|
||
|
||
var c = document.getElementById("canvas");
|
||
c.width = t;
|
||
c.height = a;
|
||
f = c.getContext("2d");
|
||
var M = new Date;
|
||
setInterval(function () {
|
||
f.clearRect(0, 0, f.canvas.width, f.canvas.height);
|
||
l(f)
|
||
}, 50)
|
||
}
|
||
|
||
// 侧边栏公告提醒 - 多RSS监控版(精准到秒+无兜底)
|
||
const COOKIE_EXPIRE_YEARS = 10;
|
||
const NOTICE_DETAIL_PATH = '/notice';
|
||
// 配置多个需要监控的RSS链接(可自由添加/删除)
|
||
const RSS_URLS = [
|
||
'https://git.anian.cc/anian/halo-theme-pix/releases.rss',
|
||
];
|
||
|
||
// 读取Cookie
|
||
function getCookie(name) {
|
||
const cookieArr = document.cookie.split('; ');
|
||
for (let cookie of cookieArr) {
|
||
const [cookieName, cookieValue] = cookie.split('=');
|
||
if (cookieName === name) {
|
||
return decodeURIComponent(cookieValue);
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// 设置Cookie
|
||
function setLongCookie(name, value) {
|
||
const date = new Date();
|
||
date.setTime(date.getTime() + (COOKIE_EXPIRE_YEARS * 365 * 24 * 60 * 60 * 1000));
|
||
const expires = "expires=" + date.toUTCString();
|
||
document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/; domain=anian.cc`;
|
||
}
|
||
|
||
function setSessionCookie(name, value) {
|
||
document.cookie = `${name}=${encodeURIComponent(value)}; path=/; domain=anian.cc`;
|
||
}
|
||
|
||
// 【核心改造】批量获取所有RSS的最新发布时间,拼接成唯一字符串
|
||
async function getAllLatestNoticeDatesFromRSS() {
|
||
try {
|
||
// 1. 批量请求所有RSS链接(并行请求)
|
||
const rssResponses = await Promise.all(
|
||
RSS_URLS.map(url => fetch(url))
|
||
);
|
||
|
||
// 2. 检查所有请求是否成功,失败则直接抛出错误
|
||
for (let [index, response] of rssResponses.entries()) {
|
||
if (!response.ok) {
|
||
throw new Error(`RSS ${RSS_URLS[index]} 请求失败:${response.status}`);
|
||
}
|
||
}
|
||
|
||
// 3. 解析所有RSS的XML内容
|
||
const allPubDates = [];
|
||
for (let response of rssResponses) {
|
||
const xmlText = await response.text();
|
||
const parser = new DOMParser();
|
||
const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
|
||
|
||
// 4. 获取当前RSS下所有item的pubDate(也可只取第一个即最新的)
|
||
const items = xmlDoc.querySelectorAll('item');
|
||
if (items.length === 0) continue;
|
||
|
||
// 5. 提取每个item的pubDate并格式化为「YYYY-MM-DD HH:mm:ss」
|
||
const itemDates = Array.from(items).map(item => {
|
||
const pubDateStr = item.querySelector('pubDate').textContent;
|
||
const pubDate = new Date(pubDateStr);
|
||
// 格式化:年-月-日 时:分:秒(精准到秒,避免同日多版本)
|
||
return `${pubDate.getFullYear()}-${String(pubDate.getMonth() + 1).padStart(2, '0')}-${String(pubDate.getDate()).padStart(2, '0')}-${String(pubDate.getHours()).padStart(2, '0')}-${String(pubDate.getMinutes()).padStart(2, '0')}-${String(pubDate.getSeconds()).padStart(2, '0')}`;
|
||
});
|
||
|
||
// 6. 取当前RSS的最新时间(数组最后一个是最早,第一个是最新),加入总列表
|
||
allPubDates.push(itemDates[0]);
|
||
}
|
||
|
||
// 7. 去重+按时间降序排序,拼接成唯一字符串(确保顺序固定)
|
||
const uniqueDates = [...new Set(allPubDates)].sort((a, b) => new Date(b) - new Date(a));
|
||
const combinedDateStr = uniqueDates.join('_'); // 用_分隔多个日期
|
||
|
||
if (!combinedDateStr) {
|
||
console.warn('获取最新版本失败');
|
||
}
|
||
|
||
return combinedDateStr;
|
||
|
||
} catch (error) {
|
||
console.error('获取RSS日期失败:', error);
|
||
// 【关键】失败时返回null,不兜底
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 标记已读(接收拼接后的日期字符串)
|
||
function markAsRead(combinedDateStr) {
|
||
if (!combinedDateStr) return; // 无有效日期则不操作
|
||
const noticeBubble = document.getElementById('noticeBubble');
|
||
const noticeBtn = document.getElementById('noticeBtn');
|
||
if (!noticeBubble || !noticeBtn) return;
|
||
|
||
setLongCookie('latest_notice_date', combinedDateStr);
|
||
noticeBubble.classList.remove('show');
|
||
noticeBtn.classList.remove('has-notice');
|
||
}
|
||
|
||
// 检测公告详情页并标记已读
|
||
function checkNoticeDetailPage(combinedDateStr) {
|
||
if (!combinedDateStr) return; // 无有效日期则不检查
|
||
const currentPath = window.location.pathname.replace(/\/$/, '');
|
||
const local_notice = getCookie('latest_notice_date');
|
||
const hasUnread = !local_notice || local_notice !== combinedDateStr;
|
||
|
||
if (currentPath === NOTICE_DETAIL_PATH && hasUnread) {
|
||
markAsRead(combinedDateStr);
|
||
}
|
||
}
|
||
|
||
// 全局事件委托(修改版:复用初始化时的LATEST_NOTICE_DATE,不重新请求RSS)
|
||
function bindGlobalNoticeEvents(combinedDateStr) {
|
||
if (document.body.dataset.noticeEventsBound) return;
|
||
|
||
document.addEventListener('click', (e) => {
|
||
const noticeBtn = document.getElementById('noticeBtn');
|
||
if (noticeBtn && (e.target === noticeBtn || noticeBtn.contains(e.target))) {
|
||
markAsRead(combinedDateStr);
|
||
}
|
||
});
|
||
|
||
document.body.dataset.noticeEventsBound = 'true';
|
||
}
|
||
|
||
// 异步初始化(无兜底逻辑)
|
||
async function initNoticeTip() {
|
||
// 1. 获取所有RSS的拼接日期字符串,失败则直接终止
|
||
const combinedDateStr = await getAllLatestNoticeDatesFromRSS();
|
||
if (!combinedDateStr) return; // 【核心】RSS失败则不检查、不显示提醒
|
||
|
||
const noticeBubble = document.getElementById('noticeBubble');
|
||
const noticeBtn = document.getElementById('noticeBtn');
|
||
if (!noticeBubble || !noticeBtn) return;
|
||
|
||
const local_notice = getCookie('latest_notice_date');
|
||
const hasUnread = !local_notice || local_notice !== combinedDateStr;
|
||
|
||
// 2. 只有RSS获取成功,才判断并显示/隐藏提醒
|
||
if (hasUnread) {
|
||
noticeBubble.classList.add('show');
|
||
noticeBtn.classList.add('has-notice');
|
||
} else {
|
||
noticeBubble.classList.remove('show');
|
||
noticeBtn.classList.remove('has-notice');
|
||
}
|
||
bindGlobalNoticeEvents(combinedDateStr);
|
||
checkNoticeDetailPage(combinedDateStr);
|
||
}
|
||
|
||
// 测速侧边栏
|
||
const bubble = document.getElementById("anianxBubble"),
|
||
bubbleText = document.getElementById("anianxBubbleText"),
|
||
group = document.querySelector(".anianx-group"),
|
||
main = document.querySelector('[data-anianx-type="main"]'),
|
||
test = document.querySelector('[data-anianx-type="test"]'),
|
||
sub = document.querySelector('[data-anianx-type="sub"]');
|
||
let speedLock = false;
|
||
let xianlu = 0;
|
||
const hostname = location.hostname;
|
||
|
||
function moveArrow(btn) {
|
||
const btnRect = btn.getBoundingClientRect(),
|
||
groupRect = group.getBoundingClientRect(),
|
||
center = (btnRect.left - groupRect.left) + (btnRect.width / 2);
|
||
bubble.style.setProperty("--anianx-arrow", center + "px");
|
||
}
|
||
|
||
if (hostname === "anian.cc") {
|
||
xianlu = 1;
|
||
main.classList.add("anianx-fixed");
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = "当前为主线路";
|
||
moveArrow(main);
|
||
} else if (hostname === "www.anian.cc") {
|
||
xianlu = 2;
|
||
sub.classList.add("anianx-fixed");
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = "当前为副线路";
|
||
moveArrow(sub);
|
||
} else {
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = "当前线路未知";
|
||
moveArrow(test);
|
||
}
|
||
|
||
main.addEventListener("click", () => {
|
||
if (main.classList.contains("anianx-fixed")) {
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = "当前为主线路";
|
||
} else {
|
||
bubbleText.classList.add("anianx-loading");
|
||
bubbleText.innerText = "正在切换至主线路";
|
||
// 1. 获取当前滚动位置
|
||
const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
|
||
document.cookie = `scrollParam=${currentScrollTop}; path=/; domain=anian.cc`;
|
||
const finalUrl = main.dataset.anianxHref + location.pathname +
|
||
location.search + location.hash;
|
||
// 3. 执行跳转
|
||
location.href = finalUrl;
|
||
}
|
||
moveArrow(main);
|
||
});
|
||
|
||
sub.addEventListener("click", () => {
|
||
if (sub.classList.contains("anianx-fixed")) {
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = "当前为副线路";
|
||
} else {
|
||
bubbleText.classList.add("anianx-loading");
|
||
bubbleText.innerText = "正在切换至副线路";
|
||
// 1. 获取当前滚动位置
|
||
const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
|
||
// 2. 拼接URL参数(保留原有逻辑 + 添加scrollTop参数)
|
||
const baseUrl = sub.dataset.anianxHref + location.pathname + location.search;
|
||
document.cookie = `scrollParam=${currentScrollTop}; path=/; domain=anian.cc`;
|
||
const finalUrl = baseUrl + location.hash;
|
||
// 3. 执行跳转
|
||
location.href = finalUrl;
|
||
}
|
||
moveArrow(sub);
|
||
});
|
||
|
||
function loadMultiplePages(pageCount, type = null, currentCount = 1) {
|
||
return new Promise((resolve, reject) => {
|
||
const configs = {
|
||
moment: {
|
||
paginator: "#t_pagination a",
|
||
listContainer: ".moment_list",
|
||
itemSelector: ".p_item",
|
||
afterLoad: () => {
|
||
typeof getMomentAudio === 'function' && getMomentAudio();
|
||
typeof initAgree === 'function' && initAgree();
|
||
window.lazyLoadInstance && lazyLoadInstance.update();
|
||
typeof initializeMomentFold === 'function' && initializeMomentFold();
|
||
// typeof modify_moment_video_size === 'function' && modify_moment_video_size();
|
||
}
|
||
},
|
||
gallery: {
|
||
paginator: "#p_pagination a",
|
||
listContainer: ".gallery-photos",
|
||
itemSelector: ".gallery-photo",
|
||
afterLoad: () => {
|
||
window.pix && typeof pix.initGalleryPhotos === 'function' && pix.initGalleryPhotos();
|
||
}
|
||
}
|
||
};
|
||
|
||
if (!type) {
|
||
if ($("#t_pagination").length) type = 'moment';
|
||
else if ($("#p_pagination").length) type = 'gallery';
|
||
else {
|
||
const errMsg = "[loadMultiplePages] 未找到分页器,无法识别加载类型";
|
||
// console.error(errMsg);
|
||
reject(errMsg);
|
||
return;
|
||
}
|
||
}
|
||
|
||
const config = configs[type];
|
||
const $paginationBtn = $(config.paginator);
|
||
const nextHref = $paginationBtn.attr('data');
|
||
|
||
if (currentCount > pageCount) {
|
||
// console.log(`[${type}] 批量加载完成,共${pageCount}页`);
|
||
resolve();
|
||
return;
|
||
}
|
||
|
||
if (!nextHref) {
|
||
// console.log(`[${type}] 已无更多内容`);
|
||
$paginationBtn.hide();
|
||
resolve();
|
||
return;
|
||
}
|
||
$paginationBtn.prop('disabled', true);
|
||
const $pagingWrapper = $paginationBtn.closest('.post-paging');
|
||
if (type === 'gallery' && $pagingWrapper.length) {
|
||
$pagingWrapper.data('origin-html', $pagingWrapper.html());
|
||
$pagingWrapper.html('<div uk-spinner></div>');
|
||
}
|
||
$.ajax({
|
||
type: "GET",
|
||
url: nextHref,
|
||
success: function (html) {
|
||
const $html = $(html);
|
||
const items = $html.find(`${config.listContainer} ${config.itemSelector}`);
|
||
|
||
if (items.length > 0) {
|
||
$(config.listContainer).append(items.fadeIn(300));
|
||
const newHref = $html.find(config.paginator).attr("data");
|
||
if (type === 'gallery' && $pagingWrapper.length) {
|
||
$pagingWrapper.html(`<a>${Theme.site_page}</a>`);
|
||
}
|
||
const $newBtn = $(config.paginator);
|
||
if (newHref) {
|
||
$newBtn.attr("data", newHref).show().prop('disabled', false);
|
||
$newBtn.html(`${Theme.site_page}`);
|
||
} else {
|
||
$newBtn.hide();
|
||
}
|
||
config.afterLoad();
|
||
loadMultiplePages(pageCount, type, currentCount + 1)
|
||
.then(resolve)
|
||
.catch(reject);
|
||
} else {
|
||
$(config.paginator).hide();
|
||
resolve();
|
||
}
|
||
},
|
||
error: function () {
|
||
const errMsg = `[${type}] 第${currentCount}页加载失败`;
|
||
// console.log(errMsg);
|
||
$(config.paginator).prop('disabled', false);
|
||
reject(errMsg);
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
function initjump() {
|
||
const urlParams = new URLSearchParams(window.location.search);
|
||
const page = document.cookie.split('; ').find(c => c.startsWith('page='))?.split('=')[1] ? decodeURIComponent(document.cookie.split('; ').find(c => c.startsWith('page='))?.split('=')[1]) : null;
|
||
const scrollTop = document.cookie.split('; ').find(c => c.startsWith('scrollParam='))?.split('=')[1] ? decodeURIComponent(document.cookie.split('; ').find(c => c.startsWith('scrollParam='))?.split('=')[1]) : null;
|
||
document.cookie = "scrollParam=; path=/; domain=anian.cc; expires=Thu, 01 Jan 1970 00:00:00 GMT";
|
||
const loadPageTask = () => {
|
||
return new Promise((resolve) => {
|
||
const timeout = setTimeout(() => {
|
||
// console.warn("页面加载超时,强制执行滚动");
|
||
resolve();
|
||
}, 3000);
|
||
|
||
if (page && !isNaN(page)) {
|
||
const targetPage = Number(page) - 1;
|
||
loadMultiplePages(targetPage)
|
||
.then(() => {
|
||
clearTimeout(timeout);
|
||
resolve();
|
||
})
|
||
.catch(() => {
|
||
clearTimeout(timeout);
|
||
resolve();
|
||
});
|
||
} else {
|
||
clearTimeout(timeout);
|
||
resolve();
|
||
}
|
||
});
|
||
};
|
||
|
||
if (scrollTop && !isNaN(scrollTop)) {
|
||
loadPageTask().then(() => {
|
||
if (xianlu === 1) cocoMessage.success('已成功切换到主线路');
|
||
else if (xianlu === 2) cocoMessage.success('已成功切换到副线路');
|
||
|
||
const recordScroll = Number(scrollTop);
|
||
const maxScroll = document.documentElement.scrollHeight - window.innerHeight;
|
||
const scrollDistance = Math.min(recordScroll, maxScroll);
|
||
const scrollSpeed = 1;
|
||
const minDuration = 100;
|
||
const maxDuration = 1000;
|
||
const dynamicDuration = Math.min(Math.max(scrollDistance / scrollSpeed, minDuration), maxDuration);
|
||
|
||
if (recordScroll > maxScroll && (recordScroll - maxScroll) > 200) {
|
||
cocoMessage.warning('请手动加载以恢复原线路内容');
|
||
$('html, body').animate({ scrollTop: maxScroll }, dynamicDuration);
|
||
} else {
|
||
$('html, body').animate({ scrollTop: recordScroll }, dynamicDuration);
|
||
}
|
||
|
||
urlParams.delete('scrollTop');
|
||
const newUrl = window.location.pathname + (urlParams.toString() ? `?${urlParams.toString()}` : '') + window.location.hash;
|
||
window.history.replaceState({}, document.title, newUrl);
|
||
});
|
||
}
|
||
}
|
||
|
||
test.addEventListener("click", () => {
|
||
if (speedLock) return;
|
||
speedLock = true;
|
||
bubbleText.classList.add("anianx-loading");
|
||
bubbleText.innerText = "测速中";
|
||
moveArrow(test);
|
||
speedTestWithTimeout(7500).then(result => {
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = result;
|
||
}).catch(() => {
|
||
bubbleText.classList.remove("anianx-loading");
|
||
bubbleText.innerText = "请检查网络或切换线路";
|
||
}).finally(() => {
|
||
speedLock = false;
|
||
});
|
||
});
|
||
|
||
function speedTestWithTimeout(timeout) {
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), timeout);
|
||
return new Promise(async (resolve, reject) => {
|
||
try {
|
||
const t0 = Date.now();
|
||
const res = await fetch(`/upload/%E4%B8%8B%E8%BD%BD%20(9).mp4?t=${Date.now()}`, {
|
||
signal: controller.signal
|
||
});
|
||
const blob = await res.blob();
|
||
const size = blob.size;
|
||
const sec = (Date.now() - t0) / 1000;
|
||
const mbps = ((size * 8) / (sec * 1024 * 1024)).toFixed(2);
|
||
clearTimeout(timer);
|
||
resolve("正常:" + mbps + " Mbps");
|
||
} catch (e) {
|
||
clearTimeout(timer);
|
||
reject(e);
|
||
}
|
||
});
|
||
}
|
||
|
||
// 侧边栏订阅函数
|
||
async function handleSubscribe(event) {
|
||
event.preventDefault();
|
||
|
||
const form = event.target;
|
||
const input = form.querySelector(".subscribe-input");
|
||
const btn = form.querySelector(".subscribe-btn");
|
||
const msg = document.getElementById("subscribe-message");
|
||
|
||
const email = input.value.trim();
|
||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
||
return show("请输入正确格式的邮箱地址", "error");
|
||
}
|
||
|
||
btn.disabled = true;
|
||
show("正在提交…");
|
||
|
||
try {
|
||
const res = await fetch(
|
||
"https://anian.cc/apis/api.flow.post.kunkunyu.com/v1alpha1/follows/-/submit",
|
||
{
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email })
|
||
}
|
||
);
|
||
|
||
if (res.status === 200) {
|
||
show("订阅成功", "success");
|
||
input.value = "";
|
||
} else {
|
||
show("您已订阅过", "warning");
|
||
}
|
||
} catch {
|
||
show("网络错误,请稍后再试", "error");
|
||
}
|
||
|
||
btn.disabled = false;
|
||
|
||
function show(text, type) {
|
||
msg.textContent = text;
|
||
msg.className = `subscribe-message ${type}`;
|
||
}
|
||
}
|
||
|
||
// 图库兼容视频监听刷新排版
|
||
let wfTimer = null;
|
||
document.addEventListener('loadedmetadata', function (e) {
|
||
if (
|
||
e.target.tagName === 'VIDEO' &&
|
||
e.target.closest('.gallery-photos')
|
||
) {
|
||
clearTimeout(wfTimer);
|
||
wfTimer = setTimeout(() => {
|
||
waterfall('.gallery-photos');
|
||
}, 300);
|
||
}
|
||
}, true);
|
||
|
||
function initBlog() {
|
||
pix.initTopBar(),
|
||
pix.getMsg(),
|
||
initAgree(),
|
||
pix.initGalleryPhotos(),
|
||
pix.loadLightbox(),
|
||
pix.topCategoriesBarScroll(),
|
||
pix.topTableBarScroll(),
|
||
getMomentAudio(),
|
||
Theme.toc.all_open && autotree(),
|
||
|
||
highlightActiveMenu(),
|
||
syncFooterWithAudioState(),
|
||
initializeMomentFold(),
|
||
nextBanner()
|
||
|
||
}
|
||
|
||
pix.roleMoments();
|
||
initBlog();
|
||
|
||
setPageGrayscale();
|
||
anian_handleLunarCookie();
|
||
updateMusicBtnColor('default');
|
||
initGreenDigitalClock();
|
||
initNoticeTip();
|
||
initjump();
|
||
initTagSwitch();
|
||
|
||
|
||
|