// ==UserScript== // @name 知乎样式修改器 // @namespace http://tampermonkey.net/ // @version 1.5.2 // @description 知乎样式自定义修改器-支持夜间模式、模块隐藏、可配置及自定义样式、图片全部可预览、过滤广告等 // @author pufferfish // @match *://www.zhihu.com/* // @match *://zhuanlan.zhihu.com/* // @grant unsafeWindow // @grant GM_setValue // @grant GM_getValue // @grant GM_listValues // @run-at document-start // @require https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js // @downloadURL none // ==/UserScript== (function () { 'use strict' // 开发使用 勿动 ---- start const isDev = false const INNER_HTML = null const INNER_CSS = null // 开发使用 勿动 ---- end let pfConfig = { versionHeart: '1200', // 版心宽度 positionAnswer: 'left', positionAnswerIndex: '1', // 优先级 positionCreation: 'right', positionCreationIndex: '2', positionTable: 'right', positionTableIndex: '3', positionFavorites: 'left', positionFavoritesIndex: '4', positionFooter: 'right', positionFooterIndex: '5', stickyLeft: false, // 首页左侧栏是否固定 stickyRight: false, // 首页右侧栏是否固定 zoomAnswerImage: '100px', // 图片缩放大小 hidden 100px 200px 400px default titleIco: '', // 网页标题logo图 title: '', // 网页标题 colorBackground: '#ffffff', // 背景色 colorsBackground: [], colorTheme: '#0066ff', colorsTheme: [], customizeCss: '', questionTitleTag: true, // 内容标题添加类别标签 // 悬浮模块 start ---------------- suspensionHomeTab: false, // 问题列表切换 suspensionHomeTabPo: 'left: 20px; top: 100px;', // 定位 suspensionHomeTabFixed: false, suspensionHomeTabStyle: 'transparent', // 样式 suspensionFind: false, // 顶部发现模块 suspensionFindPo: 'left: 10px; top: 380px;', suspensionFindFixed: false, suspensionFindStyle: 'transparent', // suspensionSearch: false, // 搜索栏 // suspensionSearchPo: 'left: 200px; top: 100px;', suspensionUser: false, // 个人中心 suspensionUserPo: 'right: 60px; top: 100px;', suspensionUserFixed: false, // 悬浮模块 end ------------------ // 隐藏内容模块 start -------- hiddenAnswerRightFooter: true, // 回答页面右侧内容 hiddenLogo: false, // logo hiddenHeader: false, // header hiddenHeaderScroll: false, // 顶部滚动header hiddenItemActions: false, // 回答操作 hiddenAnswerText: false, // 回答操作文字 hiddenQuestionShare: false, // 问题分享 hiddenQuestionTag: false, // 问题话题 hiddenQuestionActions: false, // 问题操作栏 hiddenReward: false, // 赞赏按钮 hiddenZhuanlanTag: false, // 专栏回答关联话题 hiddenListImg: false, // 问题列表图片 hiddenReadMoreText: true, // 阅读全文文字 hiddenAD: true, // 广告 hiddenAnswerRights: false, // 收藏喜欢举报按钮 hiddenAnswerRightsText: false, // 收藏喜欢举报按钮文字 hiddenAnswers: false, // 问题列表回答内容 hiddenHotListWrapper: false, // 热榜榜单TAG // 隐藏内容模块 end -------- } let pfConfigCache = {} // 缓存初始配置 // 使用位置颜色配置来解决有关版本更新颜色列表未更新的问题 const colorsLocation = { colorsBackground: ['#ffffff', '#15202b', '#000000', 'bisque', '#FAF9DE'], colorsTheme: ['#0066ff', '#ffad1f', '#e0245e', '#f45d22', '#17bf63', '#794bc4'] } // 背景色对应名称 const backgroundText = { '#ffffff': '默认', '#15202b': '黯淡', '#000000': '纯黑', 'bisque': '护眼红', '#FAF9DE': '杏仁黄', } const backgroundOp = { '#FAF9DE': '#fdfdf2', 'bisque': '#fff4e7' } let thisPageTitle = '' // 缓存页面原标题 let cacheColors = {} // 缓存颜色列表 let firstInitColors = true // 是否第一次加载颜色模块 let bodySize = 0 let bodySizePrev = 0 // 缓存的doms const doms = { positionDoms: {}, // 首页原右侧元素 headerDoms: {}, // header内元素 } const findEvent = { creator: { fun: null, num: 0, isFind: false }, header: { fun: null, num: 0, isFind: false }, } /** * 存储使用油猴自己的GM存储,解决数据不共通的问题,添加localStorage与GM判断,获取最新存储 */ const myStorage = { set: async (name, value) => { let v = value if (name === 'pfConfig') { // 如果是pfConfig则添加时间戳 const valueParse = JSON.parse(value) valueParse.t = +new Date() v = JSON.stringify(valueParse) } localStorage.setItem(name, v) await GM_setValue(name, v) }, get: async (name) => { const config = await GM_getValue(name) const configLocal = localStorage.getItem(name) let c = config if (name === 'pfConfig') { // 如果是pfConfig则通过时间戳t来获取最新配置 const cParse = config ? JSON.parse(config) : null const cLParse = configLocal ? JSON.parse(configLocal) : null c = !cParse && !cLParse ? '' : !cParse ? configLocal : !cLParse ? config : cParse.t < cLParse.t ? configLocal : config } return c } } /** * 点击方法汇总 */ const myClick = { // 开启设置弹窗 openModal: () => { $('.pf-mark')[0].style.display = 'block' initScrollModal() stopScroll() }, // 关闭设置弹窗 hideModal: () => { $('.pf-mark')[0].style.display = 'none' recoverScroll() }, // 导出配置 exportConfig: async () => { const config = await myStorage.get('pfConfig') let link = document.createElement('a') link.href = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(config) link.download = '配置.txt' document.body.appendChild(link) link.click() document.body.removeChild(link) }, // 导入配置 importConfig: async () => { const configImport = $('[name=configImport]')[0].value const config = JSON.parse(configImport) pfConfig = getPfConfigAfterFormat(config) await myStorage.set('pfConfig', JSON.stringify(pfConfig)) initDataOnDocumentStart() initData() }, // 恢复默认配置 restoreConfig: async () => { let isUse = confirm('是否启恢复默认配置?\n该功能会覆盖当前配置,建议先将配置导出保存') if (isUse) { pfConfig = getPfConfigAfterFormat(pfConfigCache) await myStorage.set('pfConfig', JSON.stringify(pfConfig)) initDataOnDocumentStart() initData() } }, // 开启预览弹窗 openPreview: (src) => { $('.pf-preview-img')[0].src = src $('.pf-preview')[0].style.display = 'block' stopScroll() }, // 关闭预览弹窗 hidePreview: () => { $('.pf-preview')[0].style.display = 'none' $('.pf-preview-img')[0].src = '' recoverScroll() }, // 启用极简模式 useSimple: async () => { let isUse = confirm('是否启用极简模式?\n该功能会覆盖当前配置,建议先将配置导出保存') if (isUse) { const config = { versionHeart: '800', positionAnswer: 'hidden', positionAnswerIndex: '1', positionCreation: 'hidden', positionCreationIndex: '2', positionTable: 'hidden', positionTableIndex: '3', positionFavorites: 'hidden', positionFavoritesIndex: '4', positionFooter: 'hidden', positionFooterIndex: '5', stickyLeft: false, stickyRight: false, zoomAnswerImage: '100px', customizeCss: '', usePresetStyle: true, hiddenAnswerRightFooter: true, hiddenLogo: true, hiddenHeader: true, hiddenHeaderScroll: true, hiddenItemActions: true, hiddenAnswerText: false, hiddenQuestionShare: true, hiddenQuestionTag: true, hiddenQuestionActions: true, hiddenReward: true, hiddenZhuanlanTag: true, hiddenListImg: true, hiddenReadMoreText: true, hiddenAD: true, hiddenAnswerRights: true, hiddenAnswerRightsText: false, hiddenAnswers: true, hiddenHotListWrapper: true, suspensionHomeTab: true, suspensionHomeTabFixed: true, suspensionHomeTabPo: 'left: 20px; top: 100px;', suspensionHomeTabStyle: 'transparent', questionTitleTag: true, suspensionFind: false, suspensionFindFixed: false, suspensionFindPo: 'left: 10px; top: 380px;', suspensionFindStyle: 'transparent', suspensionUser: true, suspensionUserFixed: true, suspensionUserPo: 'right: 60px; top: 100px;', } pfConfig = getPfConfigAfterFormat(config) await myStorage.set('pfConfig', JSON.stringify(pfConfig)) initDataOnDocumentStart() initData() } } } /** * 绑定页面元素的点击拖动方法 * 最外层函数不使用箭头函数为了能获取到自己的this */ const myMove = { init: function (eventName, configName, name) { const e = $(eventName)[0] // 保存当前元素点击事件 if (e) { this.clicks[configName] = e.click e.onmousedown = (ev) => { if (pfConfig[`${name}Fixed`]) { // 固定则跳出 return } const event = window.event || ev const dx = event.clientX - e.offsetLeft const dy = event.clientY - e.offsetTop const rx = e.offsetWidth + e.offsetLeft - event.clientX // 按下拖动 document.onmousemove = (ev) => { var event = window.event || ev const useL = this.useL.find(i => i === name) let evenLeft = 0 let evenRight = 0 if (useL) { const left = event.clientX - dx evenLeft = left <= 0 ? 0 : left >= window.innerWidth - e.offsetWidth ? window.innerWidth - e.offsetWidth : left e.style.left = evenLeft + 'px' } else { // 用body替代window获取宽度来解决右侧滚动条宽度不一致问题 const right = ($('body')[0].offsetWidth - event.clientX) - rx evenRight = right <= 0 ? 0 : right >= $('body')[0].offsetWidth - e.offsetWidth ? $('body')[0].offsetWidth - e.offsetWidth : right e.style.right = evenRight + 'px' } const top = event.clientY - dy const evenTop = top <= 0 ? 0 : top >= window.innerHeight - e.offsetHeight ? window.innerHeight - e.offsetHeight : top // 元素不能超过页面宽高 e.style.top = evenTop + 'px' this.isMove = true this.timer[configName] && clearTimeout(this.timer[configName]) this.timer[configName] = setTimeout(async () => { clearTimeout(this.timer[configName]) pfConfig[configName] = `${useL ? `left: ${evenLeft}px;` : `right: ${evenRight}px;`}top: ${evenTop}px;` await myStorage.set('pfConfig', JSON.stringify(pfConfig)) }, 500) } // 抬起停止拖动 document.onmouseup = () => { document.onmousemove = null document.onmouseup = null e.onclick = (e) => { // 如果模块被移动则移除默认点击事件 // 否则返回原有点击事件 if (this.isMove) { this.isMove = false return e.preventDefault && e.preventDefault() } else { return this.clicks[configName] } } } if (e.preventDefault) { e.preventDefault() } else { return false } } } }, destroy: function (eventName) { const e = $(eventName)[0] e && (e.onmousedown = null) }, isMove: false, clicks: {}, timer: {}, useL: ['suspensionHomeTab', 'suspensionFind'], // 使用left定位的name useR: ['suspensionUser'], // 使用right定位的name } function initData () { thisPageTitle = document.title document.querySelectorAll('.pf-input').forEach((even) => { switch (even.type) { case 'radio': if (pfConfig[even.name] && even.value === pfConfig[even.name]) { even.checked = true } break case 'checkbox': even.checked = pfConfig[even.name] || false break case 'select-one': if (pfConfig[even.name]) { for (let i = 0; i < even.length; i++) { if (even[i].value === pfConfig[even.name]) { even[i].selected = true } } } break case 'text': if (even.name === 'title' || even.name === 'customizeCss') { even.name === 'title' && (even.value = pfConfig.title || document.title) even.name === 'customizeCss' && (even.value = pfConfig['customizeCss']) } else { even.value = pfConfig[even.name] } break } even.onchange = (e) => { switch (e.target.type) { case 'checkbox': throttle(onCheckboxChanger(e.target)) break case 'radio': case 'text': throttle(onConfigChanger(e.target)) break case 'select-one': throttle(onSelectChanger(e.target)) break } } }) initPositionPage() cacheHeader() changeTitleIco() changeTitle() initColorsList() cSuspensionStyle('suspensionHomeTab') } // 缓存header内元素 function cacheHeader () { // 查找header内的三个元素 if (!findEvent.header.isFind) { findEvent.header.fun && clearTimeout(findEvent.header.fun) findEvent.header.fun = setTimeout(() => { clearTimeout(findEvent.header.fun) if (findEvent.header.num < 100) { if ($('.AppHeader-inner')[0]) { findEvent.header.isFind = true doms.headerDoms = { suspensionFind: { class: '.AppHeader-inner .AppHeader-Tabs', even: $('.AppHeader-inner .AppHeader-Tabs'), index: 1 }, // suspensionSearch: { class: '.AppHeader-inner .AppHeader-SearchBar', even: $('.AppHeader-inner .AppHeader-SearchBar'), index: 2 }, suspensionUser: { class: '.AppHeader-inner .AppHeader-userInfo', even: $('.AppHeader-inner .AppHeader-userInfo'), index: 3 }, } } findEvent.header.num++ cacheHeader() } }, 100) return } // 直接使用eventName中的顺序,减少一次循环排序 const eventNames = ['suspensionFind', 'suspensionUser'] // const eventNames = ['suspensionFind', 'suspensionSearch', 'suspensionUser'] eventNames.forEach((name) => { if (pfConfig[name]) { doms.headerDoms[name].even.addClass(`position-${name}`) $('body').append(doms.headerDoms[name].even) cSuspensionStyle(name) } else { doms.headerDoms[name].even.removeClass(`position-${name}`) doms.headerDoms[name].even.removeAttr('style', '') $('.AppHeader-inner').append(doms.headerDoms[name].even) } }) initCSSVersion() } // 加载两侧数据 function initPositionPage () { if (!findEvent.creator.isFind) { findEvent.creator.fun && clearTimeout(findEvent.creator.fun) findEvent.creator.fun = setTimeout(() => { clearTimeout(findEvent.creator.fun) if (findEvent.creator.num < 100) { // 如果查找次数小于100次就继续查找 // 循环定时直到存在创作中心 if ($('.GlobalSideBar-creator')[0]) { findEvent.creator.isFind = true doms.positionDoms = { positionAnswer: { class: 'GlobalWrite', even: $('.GlobalWrite') }, positionCreation: { class: 'CreatorEntrance', even: $('.GlobalSideBar-creator') }, positionTable: { class: 'GlobalSideBar-category', even: $('.GlobalSideBar-category') }, positionFavorites: { class: 'GlobalSideBar-navList', even: $('.GlobalSideBar-navList') }, positionFooter: { class: 'Footer', even: $('.Footer') }, } } findEvent.creator.num++ initPositionPage() } }, 100) return } // 清除两侧盒子内容 $('.pf-left-container .Sticky').empty() $('.GlobalSideBar .Sticky').empty() const leftDom = [] const rightDom = [] // 添加dom Object.keys(doms.positionDoms).forEach((key) => { const e = { even: doms.positionDoms[key].even, index: Number(pfConfig[`${key}Index`]) } if (pfConfig[key] === 'left') { leftDom.push(e) } else if (pfConfig[key] === 'right') { rightDom.push(e) } }) leftDom.sort((a, b) => a.index - b.index) rightDom.sort((a, b) => a.index - b.index) leftDom.forEach(({ even }) => { $('.pf-left-container .Sticky').append(even) }) rightDom.forEach(({ even }) => { $('.GlobalSideBar .Sticky').append(even) }) // 两侧盒子不存在子元素则隐藏 $('.pf-left-container')[0] && ($('.pf-left-container')[0].style.display = $('.pf-left-container .Sticky').children().length > 0 ? 'block' : 'none') $('.GlobalSideBar')[0] && ($('.GlobalSideBar')[0].style.display = $('.GlobalSideBar .Sticky').children().length > 0 ? 'block' : 'none') } // 在加载和导入前格式化页面配置 function getPfConfigAfterFormat (config) { const c = { ...pfConfig, ...config } // 颜色列表从本js和本地存储中合并去重 Object.keys(colorsLocation).forEach((key) => { c[key] = getArrayRemoveSame([].concat(colorsLocation[key], config[key] || [])) }) return c } // 数组去重 格式为string[] function getArrayRemoveSame (arr) { const nArr = [] arr.forEach((i) => { !nArr.includes(i) && nArr.push(i) }) return nArr } // 加载颜色列表 function initColorsList () { // 第一进入时加载暂存内容 if (firstInitColors) { firstInitColors = false Object.keys(pfConfig).forEach((key) => { /^colors/.test(key) && initColorsHtml(key, pfConfig[key]) }) } else { Object.keys(pfConfig).forEach((key) => { if (/^colors/.test(key)) { // 如果配置中的颜色在缓存中不相等,则重新加载颜色元素 pfConfig[key] !== cacheColors[key] && initColorsHtml(key, pfConfig[key]) } }) } } function initColorsHtml (key, colors) { cacheColors[key] = pfConfig[key] $(`[name="${key}"]`).children().length > 0 && $(`[name="${key}"]`).empty() colors.forEach((item) => { const name = key.replace(/colors/, 'color') const dom = $(``) dom.find('input')[0].checked = item === pfConfig[name] dom.find('input')[0].onchange = (e) => { // throttle(onConfigChanger(e.target), 300) onConfigChanger(e.target) } $(`[name="${key}"]`).length && $(`[name="${key}"]`).append(dom) }) } function colorHtmlItem (name, item) { const doms = { 'colorBackground': `${backgroundText[item]}` } return doms[name] || '' } // 颜色取反 格式是16进制6位 例如用#ffffff而不是#fff function colorReverse (OldColorValue) { var OldColorValue = "0x" + OldColorValue.replace(/#/g, "") var str = "000000" + (0xFFFFFF - OldColorValue).toString(16) return '#' + str.substring(str.length - 6, str.length) } // 修改配置 select async function onSelectChanger (ev) { const { name, value } = ev pfConfig[name] = value const changerObj = { 'versionHeart': initCSSVersion, 'suspensionHomeTabStyle': initCSSVersion, 'suspensionFindStyle': initCSSVersion, } await myStorage.set('pfConfig', JSON.stringify(pfConfig)) if (/^position/.test(name)) { initPositionPage() } else { changerObj[name] && changerObj[name]() } } // 修改配置 checkbox async function onCheckboxChanger (ev) { const { name, checked } = ev pfConfig[name] = checked await myStorage.set('pfConfig', JSON.stringify(pfConfig)) const changerObj = { 'stickyLeft': stickyBetween, 'stickyRight': stickyBetween, 'suspensionHomeTab': () => { initCSSVersion() cSuspensionStyle('suspensionHomeTab') }, 'suspensionFind': cacheHeader, // 'suspensionSearch': cacheHeader, 'suspensionUser': cacheHeader, 'questionTitleTag': initCSSVersion, } if (/^hidden/.test(name)) { initCSSVersion() } else { changerObj[name] && changerObj[name]() } } // 悬浮模块切换样式 function cSuspensionStyle (name) { const cssObj = { 'suspensionHomeTab': '.Topstory-container .TopstoryTabs', 'suspensionFind': '.AppHeader-Tabs', // 'suspensionSearch': '.AppHeader-SearchBar', 'suspensionUser': '.AppHeader-userInfo', } if ($(`.pf-${name}`)[0]) { $(`.pf-${name}`)[0].style = pfConfig[name] ? 'display: inline-block;' : 'display: none;' } // 如果取消悬浮,则注销掉挂载的move方法 if (cssObj[name]) { pfConfig[name] ? myMove.init(cssObj[name], `${name}Po`, name) : myMove.destroy(cssObj[name]) } } // 修改配置 radio text async function onConfigChanger (ev) { const { name, value } = ev pfConfig[name] = value await myStorage.set('pfConfig', JSON.stringify(pfConfig)) const changerObj = { 'zoomAnswerImage': initCSSVersion, 'titleIco': changeTitleIco, 'colorBackground': initCSSBackground, // 'colorTheme': () => changeColorTheme(), 'title': changeTitle, 'customizeCss': changeCustomCss, } if (/^position/.test(name)) { initPositionPage() } else { changerObj[name] && changerObj[name]() } } function changeCustomCss () { const cssCustom = `` $('#pf-css-custom') && $('#pf-css-custom').remove() $('head').append(cssCustom) } // 修改页面标题 function changeTitle () { document.title = pfConfig.title || thisPageTitle } // 修改页面标题ico function changeTitleIco () { const ico = { github: '', csdn: '', juejin: '', zhihu: '', } $('#pf-ico').length && $('#pf-ico').remove() ico[pfConfig.titleIco] && $('head').append(ico[pfConfig.titleIco]) } // 修改版心方法 function initCSSVersion () { const cssVersion = '' $('#pf-css-version') && $('#pf-css-version').remove() $('head').append(cssVersion) } // 悬浮模块颜色填充 function vSuspensionColor (value) { // 跟页面背景颜色同步 const bg = backgroundOp[pfConfig.colorBackground] || '#ffffff' const normal = { 'transparent': 'border:1px solid #999999;color:#999999;', 'filling': `border:1px solid #999999;color:#999999;background:${bg};`, } const active = { 'transparent': 'color:#0066ff!important;border-color:#0066ff!important;', 'filling': 'color:#ffffff!important;border-color:#0066ff!important;background:#0066ff!important;', } return { normal: normal[value], active: active[value], } } // 图片size调整 function vImgSize () { return pfConfig.zoomAnswerImage !== 'default' ? pfConfig.zoomAnswerImage === 'hidden' ? 'display: none!important;' : 'width:' + pfConfig.zoomAnswerImage + '!important;cursor: zoom-in!important;' : '' } // 判断版心是否为100vw 返回根据版心调整的宽度内容 function vHeart () { let v = pfConfig.versionHeart === '100%' ? pfConfig.versionHeart : pfConfig.versionHeart + 'px' return { v, vContent: `calc(${v} - 296px)`, leftSide: `calc(50vw - (${v} / 2))` } } // 加载预览图片方法,解决部分图片无法点击预览的问题 function initPreviewImg () { const images = [ document.querySelectorAll('.TitleImage'), document.querySelectorAll('.GifPlayer img'), document.querySelectorAll('.ArticleItem-image'), document.querySelectorAll('.ztext figure .content_image'), ] images.forEach((events) => { events.forEach((e) => { const src = e.src || (e.style.backgroundImage && e.style.backgroundImage.split('("')[1].split('")')[0]) e.onclick = () => myClick.openPreview(src) }) }) } const myBackground = { useFilter: (fi) => { return `html,html img,.pf-color-radio-item,iframe{${filterObj(fi)}}.zu-top,.zu-top-nav-userinfo.selected, html.no-touchevents .top-nav-profile:hover .zu-top-nav-userinfo,.top-nav-profile a{background:#ffffff!important;border-color: #eeeeee!important;}.zu-top .zu-top-nav-link,.top-nav-profile .zu-top-nav-userinfo,.top-nav-dropdown li a{color: #111f2c!important;}html.no-touchevents .top-nav-dropdown a:hover {background:#eeeeee!important}` }, useInitBackground: (bg) => { return `body,.Post-content,.HotList,.HotListNavEditPad,.ColumnPageHeader{background-color: ${bg}!important;}` + `.QuestionHeader,.Card,.HotItem,.GlobalSideBar-navList,.Recommendations-Main,.CommentsV2-withPagination,.RichContent-actions,.QuestionHeader-footer,.ContentItem-actions,.MoreAnswers .List-headerText,.Topbar,.CommentsV2-footer,.RichContent-actions.is-fixed,.Select-plainButton,.AppHeader,.ExploreRoundtableCard,.ExploreCollectionCard,.ExploreSpecialCard,.ExploreColumnCard,.ExploreHomePage-ContentSection-moreButton a,.QuestionWaiting-types,.AutoInviteItem-wrapper--desktop,.Popover-content,.Notifications-footer,.Popover-arrow:after,.Messages-footer{background-color:${backgroundOp[bg]}!important}` } } // 修改页面背景的css function initCSSBackground () { // 使用filter方法来实现夜间模式 const filter = { '#15202b': { invert: 0.7, 'hue-rotate': '180deg', contrast: 1.7 }, '#000000': { invert: 1, 'hue-rotate': '180deg' }, } const fi = filter[pfConfig.colorBackground] || '' const cssValue = fi ? myBackground.useFilter(fi) : isNotF() ? myBackground.useInitBackground(pfConfig.colorBackground) : '' const cssColor = `` $('#pf-css-background') && $('#pf-css-background').remove() $('head').append(cssColor) } // 背景颜色选择不是#ffffff function isNotF () { return pfConfig.colorBackground !== '#ffffff' } function filterObj (fi) { return `filter: ${Object.keys(fi).map((name) => `${name}(${fi[name]})`).join(' ')};` } // hex -> rgba function hexToRgba (hex, opacity) { return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')' } // 页面主题方法 // function changeColorTheme () { // const objBg = getCssTheme() // const cssColor = `` // $('#pf-css-theme') && $('#pf-css-theme').remove() // $('head').append(cssColor) // } function throttle (fn, timeout = 300) { let canRun = true return function () { if (!canRun) return canRun = false setTimeout(() => { fn.apply(this, arguments) canRun = true }, timeout) } } // 在打开弹窗时候停止页面滚动,只允许弹窗滚动 function stopScroll () { let top = document.body.scrollTop || document.documentElement.scrollTop document.body.style.position = 'fixed' document.body.style.top = `${-1 * top}px` } // 关闭弹窗的时候恢复页面滚动 function recoverScroll () { let top = -parseInt(document.body.style.top) document.body.style.position = 'static' document.body.style.top = 0 window.scrollTo(0, top) } function stickyBetween () { window.scrollY > 0 ? fixedPosition() : inheritPosition() } function fixedPosition () { if (pfConfig.stickyLeft && $('.pf-left-container')[0]) { $('.pf-left-container .Sticky').css({ width: $('.pf-left-container')[0].offsetWidth, position: 'fixed', left: $('.pf-left-container')[0].offsetLeft, top: $('.pf-left-container')[0].offsetTop, }) } else { $('.pf-left-container .Sticky').removeAttr('style', '') } if (pfConfig.stickyRight && $('.GlobalSideBar')[0]) { $('.GlobalSideBar .Sticky').css({ width: $('.GlobalSideBar')[0].offsetWidth, position: 'fixed', right: $('.GlobalSideBar')[0].offsetRight, top: $('.GlobalSideBar')[0].offsetTop, }) } else { $('.GlobalSideBar .Sticky').removeAttr('style', '') $('.GlobalSideBar .Sticky')[0] && ($('.GlobalSideBar .Sticky')[0].style = 'position: inherit!important') } } function inheritPosition () { $('.pf-left-container .Sticky').removeAttr('style', '') $('.GlobalSideBar .Sticky').removeAttr('style', '') $('.GlobalSideBar .Sticky')[0] && ($('.GlobalSideBar .Sticky')[0].style = 'position: inherit!important') } // 知乎外链直接打开(修改外链内容,去除知乎重定向) function initLinkChanger () { document.querySelectorAll('a.external').forEach((even) => { const evenH = even.href const href = decodeURIComponent(even.href.replace(/^https:\/\/link\.zhihu\.com\/\?target\=/, '') || '') // console.log(evenH, true, href) even.href = href }) } // // reverse color at background // function reverseCss (color, isImportant = false, name = 'color') { // return pfConfig.colorBackground !== '#ffffff' ? `${name}: ${colorReverse(color)}${isImportant ? '!important' : ''};` : '' // } // // reverse color's content at background // function reverseCssCon (color) { // return pfConfig.colorBackground !== '#ffffff' ? colorReverse(color) : color // } // function getCssTheme () { // const { colorTheme } = pfConfig // return { // bg: `.Tabs-link.is-active:after,.Button--primary.Button--blue,.BounceLoading .BounceLoading-child,.CollectionsHeader-tabsLink.is-active:after,.Favlists-privacyOptionRadio:checked, html[data-theme=dark] .Favlists-privacyOptionRadio:checked{background-color:${colorTheme}!important;}`, // bg1: `.VoteButton, html[data-theme=dark] .VoteButton,.Tag{background-color: ${hexToRgba(colorTheme, '0.1')};}`, // bg15: `.VoteButton:not(:disabled):hover, html[data-theme=dark] .VoteButton:not(:disabled):hover{background-color: ${hexToRgba(colorTheme, '0.15')};}`, // bg80: `.QuestionType--active,html[data-theme=dark] .QuestionType--active,.Button--primary.Button--blue:hover{background-color: ${hexToRgba(colorTheme, '0.8')};}`, // color: `.QuestionType--active,html[data-theme=dark] .QuestionType--active,.QuestionType--active .QuestionType-icon,html[data-theme=dark] .QuestionType--active .QuestionType-icon,.HotListNav-item.is-active,.HotListNav-sortableItem[data-hotlist-identifier=total].is-active, html[data-theme=dark] .HotListNav-sortableItem[data-hotlist-identifier=total].is-active,.TabNavBarItem-tab-MS9i.TabNavBarItem-isActive-1iXL,.pf-open-modal:hover,.TopstoryTabs-link.is-active, html[data-theme=dark] .TopstoryTabs-link.is-active,.VoteButton,.GlobalWrite-navNumber, html[data-theme=dark] .GlobalWrite-navNumber,.css-1y4nzu1,.GlobalSideBar-categoryItem .Button:hover,.Button--blue,.Tag, html[data-theme=dark] .Tag,.RichContent--unescapable.is-collapsed .ContentItem-rightButton,.CollectionsHeader-addFavlistButton, html[data-theme=dark] .CollectionsHeader-addFavlistButton,.css-1hzmtho{color: ${colorTheme}!important}`, // color8: `.TopstoryTabs-link:hover,.ContentItem-more,.ContentItem-title a:hover,.GlobalWrite--old .GlobalWrite-topItem:hover .GlobalWrite-topTitle,.GlobalWrite-navTitle:hover,a.Footer-item:hover,.RichText a.UserLink-link,.NumberBoard-item.Button:hover .NumberBoard-itemName, .NumberBoard-item.Button:hover .NumberBoard-itemValue, .NumberBoard-itema:hover .NumberBoard-itemName, .NumberBoard-itema:hover .NumberBoard-itemValue,a.QuestionMainAction:hover,.Button--link:hover,.CollectionsHeader-tabsLink:hover,.SideBarCollectionItem-title{color: ${hexToRgba(colorTheme, '0.8')}!important;}`, // border: `.Button--primary.Button--blue,.Button--blue,.Favlists-privacyOptionRadio:checked, html[data-theme=dark] .Favlists-privacyOptionRadio:checked{border-color: ${colorTheme}!important}`, // border8: `.Button--primary.Button--blue:hover{border-color: ${hexToRgba(colorTheme, '0.8')}!important;}`, // colorFFF: `.Button--primary.Button--blue{color:#ffffff!important;}`, // fill: `.CollectionsHeader-addFavlistButton svg, html[data-theme=dark] .CollectionsHeader-addFavlistButton svg{fill: ${colorTheme}!important;}` // } // } // 注入弹窗元素和默认css function initHtml () { const dom = isDev ? INNER_HTML : '
' const htmlModal = $(dom) const openButton = '