// ==UserScript==
// @name 知乎样式修改器
// @namespace http://tampermonkey.net/
// @version 1.2.2
// @description 知乎样式修改器-支持版心修改,左右模块位置调整、隐藏,夜间模式,logo隐藏,页面标头修改,自定义样式等
// @author super puffer fish
// @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'
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: '',
// 隐藏内容模块 start --------
hiddenAnswerRightFooter: true, // 回答页面右侧内容
hiddenLogo: false, // logo
hiddenHeader: false, // header
hiddenHeaderScroll: false, // 顶部滚动header
hiddenItemActions: false, // 问题底部操作模块
// 隐藏内容模块 end --------
}
let pfConfigCache = {} // 缓存初始配置
// 使用位置颜色配置来解决有关版本更新颜色列表未更新的问题
const colorsLocation = {
colorsBackground: ['#ffffff', '#15202b', '#000000'],
colorsTheme: ['#0066ff', '#ffad1f', '#e0245e', '#f45d22', '#17bf63', '#794bc4']
}
// 背景色对应名称
const backgroundText = {
'#ffffff': '默认',
'#15202b': '黯淡',
'#000000': '纯黑',
}
let thisPageTitle = '' // 缓存页面原标题
let cacheColors = {} // 缓存颜色列表
let firstInitColors = true // 是否第一次加载颜色模块
let positionDoms = {} // 缓存首页原右侧元素
let firstInitDoms = true // 是否第一次进入页面操作首页
let timeoutToFindCreator = null // 定时器---用来查找首页创作中心(因为是页面加载完成后动态写入)
const openButton = '
'
// 隐藏弹窗
function buttonModalHidden () {
$('.pf-mark')[0].style.display = 'none'
recoverScroll()
}
// 开启弹窗
function buttonModalShow () {
$('.pf-mark')[0].style.display = 'block'
initScrollModal()
stopScroll()
}
// 导出现有配置为.txt格式
async function buttonExportConfig () {
const config = await gmGetValue('pfConfig')
const url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(config)
let link = document.createElement('a')
link.href = url
link.download = '配置.txt'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
// 导入配置
async function buttonImportConfig () {
const configImport = $('[name=configImport]')[0].value
const config = JSON.parse(configImport)
pfConfig = getPfConfigAfterFormat(config)
await gmSetValue('pfConfig', JSON.stringify(pfConfig))
initData()
initDataOnDocumentStart()
}
// 恢复默认配置
async function buttonRestoreConfig () {
pfConfig = {
...pfConfigCache,
...colorsLocation,
}
await gmSetValue('pfConfig', JSON.stringify(pfConfig))
initData()
initDataOnDocumentStart()
}
function initData () {
thisPageTitle = document.title
for (let even of $('.pf-input')) {
// even.value = pfConfig[even.name]
switch (even.type) {
case 'radio':
if (pfConfig[even.name] && even.value === pfConfig[even.name]) {
even.checked = true
}
break
case 'checkbox':
if (pfConfig[even.name]) {
even.checked = true
}
break
}
if (even.name === 'title') {
even.value = pfConfig.title || document.title
}
if (even.name === 'customizeCss') {
even.value = pfConfig['customizeCss']
}
even.onchange = (e) => {
switch (e.target.type) {
case 'checkbox':
throttle(changeConfigByCheckbox(e.target), 300)
break
case 'radio':
case 'text':
throttle(changeConfig(e.target), 300)
break
}
}
}
document.querySelector('.pf-hidden-labels').onclick = (even) => {
console.log(even)
}
initPositionPage()
changeTitleIco()
initColorsList()
changeTitle()
}
// 在加载和导入前格式化页面配置
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) => {
if (!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(changeConfig(e.target), 300)
changeConfig(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)
}
// 修改配置 checkbox
async function changeConfigByCheckbox (ev) {
const { name, checked } = ev
pfConfig[name] = checked
await gmSetValue('pfConfig', JSON.stringify(pfConfig))
const changerObj = {
'stickyLeft': () => stickyBetween(),
'stickyRight': () => stickyBetween(),
// 'hiddenAnswerRightFooter': () => changeVersion(),
// 'hiddenLogo': () => changeVersion(),
}
if (/^hidden/.test(name)) {
changeVersion()
} else {
changerObj[name] && changerObj[name]()
}
}
// 修改配置 radio text
async function changeConfig (ev) {
const { name, value } = ev
pfConfig[name] = value
await gmSetValue('pfConfig', JSON.stringify(pfConfig))
const changerObj = {
'versionHeart': () => changeVersion(),
'zoomAnswerImage': () => changeVersion(),
'titleIco': () => changeTitleIco(),
'colorBackground': () => changeColorBackground(),
'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 initPositionPage () {
if (firstInitDoms) {
timeoutToFindCreator = setTimeout(() => {
clearTimeout(timeoutToFindCreator)
// 循环定时直到存在创作中心
if ($('.GlobalSideBar-creator').length) {
firstInitDoms = false
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') },
}
}
initPositionPage()
}, 100)
return
}
// 清除两侧盒子内容
$('.pf-left-container .Sticky').empty()
$('.GlobalSideBar .Sticky').empty()
const leftDom = []
const rightDom = []
// 添加dom
Object.keys(positionDoms).forEach((key) => {
const e = { even: 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 changeVersion () {
const cssVersion = ''
$('#pf-css-version') && $('#pf-css-version').remove()
$('head').append(cssVersion)
}
// 判断版心是否为100vw 返回根据版心调整的宽度内容
function vHeart () {
let v = pfConfig.versionHeart === '100vw' ? pfConfig.versionHeart : pfConfig.versionHeart + 'px'
return {
v,
vContent: `calc(${v} - 296px)`,
leftSide: `calc(50vw - (${v} / 2 + 150px))`
}
}
// 修改页面背景的css
function changeColorBackground () {
const filter = {
'#ffffff': { invert: 0, 'hue-rotate': '0' },
'#15202b': { invert: 0.7, 'hue-rotate': '180deg', contrast: 1.7 },
'#000000': { invert: 1, 'hue-rotate': '180deg' },
}
const fi = filter[pfConfig.colorBackground]
// 使用filter方法来实现夜间模式
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(' ')};`
}
// 页面主题方法
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')
}
// 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 + ')'
}
// // 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 =
''
const htmlModal = $(dom)
// $('.AppHeader-userInfo').prepend(openButton)
// $('.ColumnPageHeader-Button').prepend(openButton)
$('body').append(openButton)
$('body').append(htmlModal)
$('.pf-open-modal')[0] && ($('.pf-open-modal')[0].onclick = buttonModalShow)
$('.pf-b-close')[0].onclick = buttonModalHidden
$('.pf-export-config')[0].onclick = buttonExportConfig
$('.pf-import-config')[0].onclick = buttonImportConfig
$('.pf-restore-config')[0].onclick = buttonRestoreConfig
$('.pf-customize-css-button')[0].onclick = () => changeConfig($('[name="customizeCss"]')[0])
// 在首页加入左侧模块 用于调整创作中心 收藏夹等模块元素
const leftDom = $('')
$('.Topstory-container').prepend(leftDom)
$('.QuestionWaiting').prepend(leftDom)
// initScrollHeader()
// initScrollModal()
}
function initCss () {
const cssOwn = ''
$('head').append(cssOwn)
}
// 在启动时注入的内容
(async function () {
pfConfigCache = pfConfig
const config = await gmGetValue('pfConfig')
const nConfig = config ? JSON.parse(config) : {}
pfConfig = getPfConfigAfterFormat(nConfig)
initCss()
initDataOnDocumentStart()
})()
function initDataOnDocumentStart () {
changeVersion()
changeColorBackground()
// changeColorTheme()
changeCustomCss()
}
// 在页面加载完成时注入的内容
window.onload = () => {
initHtml()
initData()
}
window.onscroll = throttle(() => {
// initScrollHeader()
stickyBetween()
}, 100)
// // 滚动在header加入弹窗启动按钮
// function initScrollHeader () {
// if ($('.TopstoryPageHeader-aside')[0] && !$('.TopstoryPageHeader-aside .pf-open-modal')[0]) {
// $('.TopstoryPageHeader-aside').prepend(openButton)
// $('.TopstoryPageHeader-aside .pf-open-modal')[0] && ($('.TopstoryPageHeader-aside .pf-open-modal')[0].onclick = buttonModalShow)
// }
// if ($('.PageHeader.is-shown .QuestionHeader-side')[0] && !$('.PageHeader.is-shown .QuestionHeader-side .pf-open-modal')[0]) {
// $('.PageHeader.is-shown .QuestionHeader-side').prepend(openButton)
// $('.PageHeader.is-shown .QuestionHeader-side .pf-open-modal')[0] && ($('.PageHeader.is-shown .QuestionHeader-side .pf-open-modal')[0].onclick = buttonModalShow)
// }
// }
// 在弹窗滚动中加入a标签锚点配置
function initScrollModal () {
const hrefArr = []
for (let i of $('.pf-left a')) {
const id = i.href.replace(/.*#/, '')
hrefArr.push({
id,
offsetTop: $(`#${id}`)[0].offsetTop
})
}
scrollModal(hrefArr)
$('.pf-right')[0].onscroll = throttle(() => scrollModal(hrefArr), 100)
}
function scrollModal (hrefArr) {
const scHere = $('.pf-right')[0].offsetHeight / 2 + $('.pf-right')[0].scrollTop
const id = hrefArr.find((item, index) => item.offsetTop <= scHere && ((hrefArr[index + 1] && hrefArr[index + 1].offsetTop > scHere) || !hrefArr[index + 1])).id
for (let i of $('.pf-left a')) {
i.style = i.href.replace(/.*#/, '') === id ? `color: ${pfConfig.colorTheme}` : ''
}
}
// 存储使用油猴自己的GM存储,解决数据不共通的问题,添加localStorage与GM判断,获取最新存储
async function gmSetValue (name, value) {
let v = value
if (name === 'pfConfig') {
const valueParse = JSON.parse(value)
valueParse.t = +new Date()
v = JSON.stringify(valueParse)
}
localStorage.setItem(name, v)
await GM_setValue(name, v)
}
async function gmGetValue (name) {
const config = await GM_getValue(name)
const configLocation = localStorage.getItem(name)
let c = config
if (name === 'pfConfig') {
const cParse = config ? JSON.parse(config) : null
const cLParse = configLocation ? JSON.parse(configLocation) : null
c = !cParse && !cLParse
? ''
: !cParse
? configLocation
: !cLParse
? config
: cParse.t < cLParse.t
? configLocation
: config
}
return c
}
})()