"use strict"; // 夜间模式 function daynightswitch() { const key = 'nightmode'; // 夜晚模式开关 const dayswitch = $("#dayswitch"); dayswitch.toggleclass("dayswitch"); $(document.body).toggleclass("night"); if (document.body.classlist.contains('night')) { setlocalstorage(key, true); } else { setlocalstorage(key, false); } } /** * 自动切换夜间模式 */ function autodaynight() { if (window.matchmedia && window.matchmedia( '(prefers-color-scheme: dark)').matches) { setlocalstorage('nightmode', true); // 默认是日间模式,如果检测到系统处于夜间模式,则自动切换到夜间模式 checknightmode() } } function checknightmode() { const isnight = getlocalstorage('nightmode'); // 如果已经是夜间模式 if (isnight) { const dayswitch = $("#dayswitch"); dayswitch.removeclass("dayswitch"); $(document.body).addclass("night"); } } /** * 点击页面处理小屏幕目录事件 * @param target */ function documentclicktoc(target) { var moontoc = $('#moontoc') if (moontoc && moontoc.hasclass('mm-active')) { if (target.id && target.id === "moontoc") { } else if (target.id && target.id === "moonmenu") { } else if (target.id && target.classlist.contains('icon-toc')) { } else if (target.classlist.contains('moon-menu-button')) { } else if (target.classlist.contains('moon-menu-text')) { } else { togglesmalltoc() } } } function gethashcode(str, casesensitive) { if (!casesensitive) { str = str.tolowercase(); } var hash = 1315423911, i, ch; for (i = str.length - 1; i >= 0; i--) { ch = str.charcodeat(i); hash ^= ((hash << 5) + ch + (hash >> 2)); } return (hash & 0x7fffffff); } /** * 处理目录 */ function dealcontenttoc() { if (getclientwidth() > 1359) { inittoc(); scrolltocfixed(); } else { var smalltoc = $('.moon-menu-item.icon-toc'); if (smalltoc) { smalltoc.toggleclass('hidden'); // 渲染目录 initmoontoc() } $(document).click(function (e) { var target = e.target; documentclicktoc(target); }); } } /** * 处理导航菜单 */ function handlenavmenu() { if (getclientwidth() <= 800) { $('#navheader .nav').addclass('opacity-100').removeclass('opacity-0') return; } if (hidemenu) { document.addeventlistener('scroll', handlescrollmenu, false); } } function handlescrollmenu() { if (getclientwidth() <= 800) { $('#navheader .nav').addclass('opacity-100').removeclass('opacity-0') return; } var scrolltop = getscrolltop(); if (scrolltop > 29) { $('#navheader').addclass('nav-bg-fff') $('#navheader .nav').addclass('opacity-100').removeclass('opacity-0') $('#navheader .collapse-nav').hide() $('.collapse-burger').removeclass('open'); } else { $('#navheader').removeclass('nav-bg-fff') $('#navheader .nav').removeclass('opacity-100').addclass('opacity-0') $('#navheader .collapse-nav').show() } } function collapsenav() { var bugger = $('.collapse-burger'); bugger.toggleclass('open'); var nav = $('#navheader .nav'); nav.toggleclass('opacity-100') if (nav.hasclass('opacity-100')) { nav.removeclass('slideout'); nav.addclass('slidein'); } else { nav.addclass('slideout'); nav.removeclass('slidein'); } } // 图片 function loadgallery() { if ( typeof viewer !== "undefined" && document.getelementbyid("gallery-content") ) { new viewer(document.getelementbyid("gallery-content"), { toolbar: true }); } gallery() } /******************************** * * 文章页面相关 * *******************************/ function scrolltocfixed() { document.addeventlistener("scroll", tocscroll, false); } function removescrolltocfixed() { document.removeeventlistener('scroll', tocscroll, false); } function loadcodelinenumber() { if (enablelinenumber) { $('.md-content pre>code[class*="language-"]').each(function (i, block) { linenumbersblock(block); }); } if (collpasecode) { $('.md-content pre>code[class*="language-"]').each(function (i, block) { $(block).parent().wrap('
'); $(block).parent().before('code') }); } } //获取滚动条距离顶部位置 function getscrolltop() { return document.documentelement.scrolltop || document.body.scrolltop; } function tocscroll(event) { var tocid = "#toc"; var obj = $("#tocflag"); //判断元素是否存在 if (obj.length !== 1) { return false; } var tocfixed = $(tocid); var objtop = obj.offset().top - $(window).height() * 0.5; // 滚动条离页面顶端的距离 var scrolltop = getscrolltop(); var postheaderheight = $("#postheader").height(); if (scrolltop > postheaderheight / 2) { tocfixed.show(); } else { tocfixed.hide(); } var tocele = document.queryselector(tocid); if (!tocele || !tocele.getboundingclientrect()) { return; } var tocheight = tocele.getboundingclientrect().height; if (scrolltop > objtop - tocheight * 0.5) { tocfixed.addclass("toc-right-fixed"); } else { tocfixed.removeclass("toc-right-fixed"); } // 设置目录right toceleright(); event.preventdefault(); } function getclientwidth() { return document.body.clientwidth; } function inittoc() { var headerel = "h1,h2,h3,h4,h5,h6", //headers content = ".md-content"; //文章容器 tocbot.init({ tocselector: "#toc", contentselector: content, headingselector: headerel, scrollsmooth: true, headingsoffset: 0 - $("#postheader").height(), // scrollsmoothoffset: -80, // 实现点击目录精准跳转到header hasinnercontainers: false, }); $(".toc-link").each(function () { var linkcontent = $(this).html(); $(this).html('' + linkcontent); }); // 设置目录right toceleright(); } function toceleright() { var screenwidth = getclientwidth(); var tocele = document.getelementbyid("toc"); if (tocele) { tocele.style.left = (screenwidth - 800) / 2 + 820 + "px"; } } function togglealipay() { $(".qrcode-wechat").addclass("hidden"); $(".qrcode-alipay").toggleclass("hidden"); $("#wechat i").removeclass("active-bg"); $("#alipay i").toggleclass("active-bg"); } function togglewechat() { $(".qrcode-alipay").addclass("hidden"); $(".qrcode-wechat").toggleclass("hidden"); $("#alipay i").removeclass("active-bg"); $("#wechat i").toggleclass("active-bg"); } function scollto() { var postheight = $("#homeheader").height(); window.scroll({top: postheight, behavior: "smooth"}); } function generateid() { const chars = `abcdefghjkmnpqrstwxyzabcdefhijkmnprstwxyz`; let id = ``; for (let i = 0; i < 8; i++) { id += chars[math.floor(math.random() * chars.length)]; } return id; } function getbilibili(width, height, id) { return `` } function getwangyimusic(id) { return `` } const wangyi = /\[music:\s*\d+\s*\]/g; var bilibili = /\[bilibili:\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\]/g /** * 将文本转成 markdown */ function formatcontent() { var mdcontent = document.getelementbyid("original"); const persentcontent = $("#write"); if (!mdcontent || !persentcontent) { return; } // 获取原始html let originalcontent = mdcontent.innerhtml; if (typeof originalcontent === "undefined") { return false; } // 反转义原始markdown文本 originalcontent = htmldecode(originalcontent); persentcontent.empty(); persentcontent.addclass("loading"); const renderer = new marked.renderer(); renderer.heading = function (text, level, raw, slugger) { return `${text}`; }; renderer.paragraph = function (text) { // 渲染网易云音乐 var musics = text.match(wangyi); if (musics && musics.length > 0) { for (var i = 0; i < musics.length; i++) { var wangyimusic = musics[i].match(/\d+/); if (wangyimusic && wangyimusic.length > 0) { var id = wangyimusic[0]; text = text.replace(musics[i], getwangyimusic(id)); } } } // 渲染bilibili视频 var videos = text.match(bilibili); if (videos && videos.length > 0) { for (var j = 0; j < videos.length; j++) { var video = videos[j].match(/\d+/g); if (video && video.length > 0 && video.length === 3) { var aid = video[0], width = video[1], height = video[2]; text = text.replace(videos[j], getbilibili(width, height, aid)); } } } return `

${text}

` }; renderer.link = function (href, title, text) { if (href && href.startswith('#')) { return `${text}`; } return `${text}`; }; renderer.image = function (href, title, text) { const reg = /([^]*)\[([^]*)\]\(([^]*)\)/; const iscontainurl = reg.test(text); const imghtml = `${text}`; return ` ${ iscontainurl ? getimgwithurlhtml(text.match(reg), href) : imghtml } `; }; function getimgwithurlhtml(textarr, href) { return `${textarr[2]}`; } renderer.listitem = function (text, task) { if (task) { return `
  • ${text}
  • `; } return `
  • ${text}
  • `; }; renderer.blockquote = function (text) { text = text.trim(); // 去掉换行符 text = text.replace(/[\r\n]/g, "
    "); text = text.replace(/

    /g, ""); text = text.replace(/<\/p>/g, "
    "); const textarr = text.split("
    "); const context = []; for (let i = 0; i < textarr.length; i++) { if (textarr[i].trim().length === 0) { continue; } let txt = textarr[i].replace(//g, '') txt = txt.replace(/
    /g, '') context.push(`

    ${txt}

    `); } return `
    ${context.join("")}
    `; }; renderer.table = function (header, body) { if (body) { body = "" + body + ""; } return ( '
    \n' + "\n" + header + "\n" + body + "
    \n" ); }; marked.setoptions({ renderer: renderer, highlight: function (code, language) { if (enablecodehighlight) { const validlanguage = hljs.getlanguage(language) ? language : "plaintext"; return hljs.highlight(validlanguage, code).value; } return code; }, pedantic: false, gfm: true, breaks: false, sanitize: false, smartlists: true, smartypants: false, xhtml: false, }); persentcontent.empty(); persentcontent.removeclass("loading"); persentcontent.html(marked(originalcontent.trim())); mdcontent.remove(); mdcontent = null; // 代码行号 loadcodelinenumber(); // 相册 loadgallery() // 数学公式 rendermath() // 图片懒加载 lazyloadimg() return true; } /** * 反转义 html * @param text * @returns {*} * @constructor */ function htmldecode(text) { var arrentities = {lt: "<", gt: ">", nbsp: " ", amp: "&", quot: '"'}; return text.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) { return arrentities[t]; }); } /******************************* * 右下角按钮相关 */ function smoothback2top() { window.scroll({top: 0, behavior: 'smooth'}); } function smoothback2bottom() { const offsetheight = document.documentelement.offsetheight; const scrollheight = document.documentelement.scrollheight; window.scroll({top: scrollheight - offsetheight, behavior: 'smooth'}); } function ckback2top() { $('#moontoc').removeclass('mm-active'); smoothback2top(); } function ckback2bottom() { $('#moontoc').removeclass('mm-active'); smoothback2bottom(); } function ckshowcontent() { togglesmalltoc() // 模拟点击事件 $('.moon-menu-button').trigger("click"); } function togglesmalltoc() { var mooncontent = $('#moontoc') mooncontent.toggleclass('mm-active'); if (mooncontent.hasclass('mm-active')) { mooncontent.show(); } else { mooncontent.hide() } } function initmoontoc() { var headerel = 'h1,h2,h3,h4,h5,h6', //headers content = '.md-content';//文章容器 tocbot.init({ tocselector: '#moontoc', contentselector: content, headingselector: headerel, scrollsmooth: true, iscollapsedclass: '', headingsoffset: 0 - ($('#postheader').height() + 58), scrollsmoothoffset: -60, hasinnercontainers: false, }); var moontoc = $('#moontoc'); // 没有生成目录 if (moontoc && moontoc.children().length === 0) { $('.icon-toc').addclass('hidden'); } } function togglesearchbox() { $('#searchbox').toggleclass('hidden'); } function togglecircle() { var $moondot = $('g.moon-dot'); var firstcircle = $moondot.children('circle:first'); var lastcircle = $moondot.children('circle:last'); var cy = $(firstcircle).attr('cy'); if (cy === '0') { $(firstcircle).attr('cx', '0'); $(firstcircle).attr('cy', '-.8rem'); $(lastcircle).attr('cx', '0'); $(lastcircle).attr('cy', '.8rem'); } else { $(firstcircle).attr('cx', '-.8rem'); $(firstcircle).attr('cy', '0'); $(lastcircle).attr('cx', '.8rem'); $(lastcircle).attr('cy', '0'); } } function ckmoonbutton() { // 右下角的小点 togglecircle(); $('.moon-menu-items').toggleclass('item-ani'); } /** * 异步获取分页数据 * @param e */ function getdata(e) { const path = $(e).attr("path"); var pagecontainer = "#pagecontainer"; $.ajax({ type: "get", url: path, beforesend: function () { $(pagecontainer).empty(); $(pagecontainer).addclass("loading"); }, success: function (data) { $(pagecontainer).removeclass("loading"); $(pagecontainer).empty(); let result = $(data).find(pagecontainer); $(pagecontainer).append(result.children()); let page = "#pagination"; let pagination = $(data).find(page); $(page).empty(); $(page).append(pagination.children()); lazyloadimg(); if ($(data).find(".ziyan")) { // 计算时间 settimeago(); // 自言代码高亮 hljsziyancode() } }, error: function () { $(pagecontainer).empty(); $(pagecontainer).addclass("loading"); }, }); } /** * 自言查看更多 * @param e */ function getmore(e) { const path = $(e).attr("path"); var morecontainer = "#morecontainer"; var moreloading = '#pagination'; $.ajax({ type: "get", url: path, beforesend: function () { $(moreloading).empty(); $(moreloading).addclass("loading"); }, success: function (data) { $(moreloading).removeclass("loading"); $(moreloading).empty(); let result = $(data).find(morecontainer); $(morecontainer).append(result.children()); let page = "#pagination"; let pagination = $(data).find(page); $(page).empty(); $(page).append(pagination.children()); if ($(data).find(".ziyan")) { // 计算时间 settimeago(); // 自言代码高亮 hljsziyancode() } }, }); } /** * 渲染数学公式 */ function rendermath() { if (openkatex && rendermathinelement && typeof rendermathinelement !== 'undefined') { if (document.getelementbyid('write')) { rendermathinelement(document.getelementbyid('write'), katex_config) } else if (document.getelementbyid('ziyan')) { rendermathinelement(document.getelementbyid('ziyan'), katex_config) } } } /** * 懒加载图片 */ function lazyloadimg() { var imgs = document.queryselectorall('img.lazyload'); var randomimgs = document.queryselectorall('img.img-random'); //用来判断bound.top<=clientheight的函数,返回一个bool值 function isin(el) { const bound = el.getboundingclientrect(); const clientheight = window.innerheight; return bound.top <= clientheight; } //检查图片是否在可视区内,如果不在,则加载 function check() { array.from(imgs).foreach(function (el) { if (isin(el)) { loadimg(el); } }) array.from(randomimgs).foreach(function (el) { if (isin(el)) { loadrandomimgs(el); } }) } function loadimg(el) { const loaded = el.getattribute('data-loaded') if (!loaded) { el.src = el.dataset.src; el.setattribute('data-loaded', true) } } function loadrandomimgs(el) { const loaded = el.getattribute('data-loaded') if (!loaded) { var index = el.getattribute('index'); var imgindex = !index ? new date().getseconds() : index; if (el.classlist.contains('img-random') && typeof photos !== 'undefined' && photos.length > 0) { el.src = photos[imgindex % photos.length]; } el.setattribute('data-loaded', true) } } window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发 check(); } } /** * 计算时间 * @param time * @returns {string|*} */ function timeago(time) { var currenttime = new date().gettime() var between = currenttime - time var days = math.floor(between / (24 * 3600 * 1000)) if (days === 0) { var leave1 = between % (24 * 3600 * 1000) var hours = math.floor(leave1 / (3600 * 1000)) if (hours === 0) { var leave2 = leave1 % (3600 * 1000) var minutes = math.floor(leave2 / (60 * 1000)) if (minutes === 0) { var leave3 = leave2 % (60 * 1000) var seconds = math.round(leave3 / 1000) return seconds + ' 秒前' } return minutes + ' 分钟前' } return hours + ' 小时前' } if (days < 0) { return '刚刚' } if (days < 1) { return days + ' 天前' } else { return formatdate(time, 'yyyy/mm/dd hh:mm'); } } /** * 格式化时间 * @param date * @param fmt * @returns {*} */ function formatdate(date, fmt) { date = new date(date); if (/(y+)/.test(fmt)) { fmt = fmt.replace(regexp.$1, (date.getfullyear() + '').substr(4 - regexp.$1.length)); } let o = { 'm+': date.getmonth() + 1, 'd+': date.getdate(), 'h+': date.gethours(), 'm+': date.getminutes(), 's+': date.getseconds() }; for (let k in o) { if (new regexp(`(${k})`).test(fmt)) { let str = o[k] + ''; fmt = fmt.replace(regexp.$1, (regexp.$1.length === 1) ? str : padleftzero(str)); } } return fmt; } /** * * @param str * @returns {string} */ function padleftzero(str) { return ('00' + str).substr(str.length); } /** * 设置时间 */ function settimeago() { $('.time-ago').each(function () { const time = $(this).attr('time'); const timestr = timeago(new date(time)); $(this).html(timestr); }); } /** * 自言代码高亮 */ function hljsziyancode() { $('.ziyan .md-content pre code').each(function () { hljs.highlightblock(this); }); } /** * 获取本地 * @param key * @returns {null|*} */ function getlocalstorage(key) { var exp = 60 * 60 * 1000; // 一个小时的秒数 if (localstorage.getitem(key)) { var vals = localstorage.getitem(key); // 获取本地存储的值 var dataobj = json.parse(vals); // 将字符串转换成json对象 // 如果(当前时间 - 存储的元素在创建时候设置的时间) > 过期时间 var istimed = (new date().gettime() - dataobj.timer) > exp; if (istimed) { console.log("存储已过期"); localstorage.removeitem(key); return null; } else { var newvalue = dataobj.val; } return newvalue; } else { return null; } } function isquotaexceeded(e) { var quotaexceeded = false; if (e) { if (e.code) { switch (e.code) { case 22: quotaexceeded = true; break; case 1014: // firefox if (e.name === 'ns_error_dom_quota_reached') { quotaexceeded = true; } break; } } else if (e.number === -2147024882) { // ie8 quotaexceeded = true; } } return quotaexceeded; } function setlocalstorage(key, value) { var curtime = new date().gettime(); // 获取当前时间 ,转换成json字符串序列 var valuedate = json.stringify({ val: value, timer: curtime }); try { localstorage.removeitem(key) localstorage.setitem(key, valuedate); } catch (e) { // 兼容性写法 if (isquotaexceeded(e)) { console.log("error: 本地存储超过限制"); localstorage.clear(); } else { console.log("error: 保存到本地存储失败"); } } } // 相册页面 function gallery() { var $photopage = $(".photos-page"); // 判断当前是否为图库界面 if ($photopage.length < 1) { return; } // 渲染图库信息 var $masonrys = $(".masonry-gallery.gallery"); var option = { masonry: { gutter: 10, }, // layoutmode: 'masonry', // sortby: 'name', // percentposition: true, itemselector: ".gallery-item", } $masonrys.find("img.lazyload").on('load', function () { $masonrys.isotope(option); }) $("#gallery-filter li a").on("click", function () { $("#gallery-filter li a").removeclass("active"); $(this).addclass("active"); var datafilter = $(this).data("filter"); $masonrys.isotope({ filter: datafilter, }); return false; }); } $(function () { checknightmode() // 自动切换夜间模式 if (autonightmode) { autodaynight(); } // 处理导航菜单 handlenavmenu(); // 格式化markdown文章 const format = formatcontent(); // 目录相关 if (typeof tocbot !== "undefined" && document.getelementbyid("toc")) { dealcontenttoc(); } if ($('#container').find('.md-content').length > 0 && format) { return; } // 相册 loadgallery(); // 图片懒加载 lazyloadimg(); if ($('#container').find('.ziyan').length > 0) { // 计算时间 settimeago(); // 自言代码高亮 hljsziyancode() } });