【油猴】针对CSDN的美化脚本

CSDN博客页美化

美化前:
在这里插入图片描述
美化后:
在这里插入图片描述

代码:

// ==UserScript==
// @name         0【自写】CSDN博客页美化
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       Ji
// @match        https://blog.csdn.net/*
// @match        https://mp.csdn.net/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==

(function () {
  'use strict';


  function clean_rabbish() {
      var elementsToDelete = [
          '.feed-template',
          '#cknow-ai-box2',
          '.toolbar-advert',
          '.blog_container_aside',
          '.csdn-side-toolbar',
          '#asideArchive',
          '#recommendAdBox',
          '.programmer1Box',
          '.kind_person',
          '.recommend-right',
          '.tool-QRcode',
          '.sidebar-ai-guide-btn'
      ];

      for (var i = 0; i < elementsToDelete.length; i++) {
          var element = document.querySelector(elementsToDelete[i]);
          if (element != null) {
              console.log('删除元素:', element);
              element.remove();
          }
      }

      var dynamicContainer = document.querySelector('[class^="pcContainer_"]');
      if (dynamicContainer) {
          console.log('删除动态容器:', dynamicContainer);
          dynamicContainer.remove();
      }
  }

    // 执行清理
    clean_rabbish();


  function clean_vip() {
    // 获取所有具有.recommend-item-box类的元素
    var recommendBoxes = document.querySelectorAll('.recommend-item-box');
    for (var i = 0; i < recommendBoxes.length; i++) {
      var box = recommendBoxes[i];
      var links = box.querySelectorAll('a');
      for (var j = 0; j < links.length; j++) {
        var link = links[j];
        var href = link.href;
        // 判断链接中是否包含download.csdn
        if (href.indexOf('download.csdn') !== -1) {
          recommendBoxes[i].parentNode.removeChild(recommendBoxes[i]);
        }
      }
    }
  }

  function clean_follow() {
    const btn = document.getElementById('btn-readmore-zk');
    if (btn) {
      btn.click();
    }
  }


  function catelog() {
    const tocElement = document.querySelector('.toc');
    if (tocElement) {
      return;
    }
    // 1. 提取所有标题,生成目录导航
    const mainBox = document.querySelector('#mainBox');
    const headings = mainBox.querySelectorAll('h1, h2, h3, h4, h5, h6');
    if (headings.length === 1)
      return;
    const tocDiv = document.createElement('div');
    tocDiv.classList.add('toc');
    tocDiv.style = "display:flex;flex-flow: column;";

    headings.forEach(heading => {
      if (heading.textContent) {
        // 如果标题没有id属性,就自动添加一个以"heading-"开头加上索引值的id
        if (!heading.id) {
          const index = Array.from(headings).indexOf(heading);
          heading.id = `heading-${index}`;
        } const link = document.createElement('a');
        link.href = `#${heading.id}`;
        link.textContent = heading.textContent;
        const tagMatch = heading.tagName.match(/h(\d)/i);
        if (tagMatch) {
          const level = tagMatch[1];
          link.classList.add(`h${level}`);
        }
        tocDiv.appendChild(link);
      }
    });
    document.body.appendChild(tocDiv);

    // 2. 将目录导航添加到.mainBox元素的子节点中
    mainBox.appendChild(tocDiv);

    // 可选:添加滚动平滑效果(如果浏览器支持)
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
        e.preventDefault();

        const targetId = this.getAttribute('href').substring(1);
        const targetElement = document.getElementById(targetId);

        if (targetElement) {
          targetElement.scrollIntoView({
            behavior: 'smooth'
          });
        }
      });
    });


    const tocLinks = document.querySelectorAll('.toc a');
    tocLinks.forEach(link => {
      link.style.width = '100%';
      link.style.textDecoration = 'none';
      link.style.padding = '5px';
    });
  }

  // .main_father
  // .container
  // main

  function addCss() {
    const cssContent = `
body{
  background-image:none !important;
  background:white !important;
}
.toc a{
  padding: 3px 5px !important;
  margin-bottom:3px !important;
}
.h1 {
  background: #e2e5e6;
  border-radius: 5px;
  font-weight: 600;
}
.h2{
  color: #306797 !important;
  margin-left:10px;
}
.h3{
  background: #e2e5e6;
  border-radius: 5px;
  font-size:14px;
  margin-left:20px;
}
.h4{
  font-size:14px;
  margin-left:30px;
}
.h5{
  background: #e2e5e6;
  border-radius: 5px;
  font-size:14px;
  margin-left:40px;
}
.h6{
  font-size:14px;
  margin-left:50px;
}
.recommend-item-box{
  border:1px solid gray !important;
  border-radius: 5px;
  margin-bottom:5px;
}
@media (min-width: 1550px) and (max-width: 1700px) {
    .nodata .container {
        padding:0 200px;
        width: 100% !important;
        height: 100% !important;
        margin-right:0 !important;
        display:flex;
    }
}
@media (min-width: 1550px) and (max-width: 1700px) {
    .nodata .container main {
        flex:7;
        height: 100%;
        overflow-y: auto;
        background: e8e8e8;
    }
}
.toc {
    height: 100%;
    overflow-y: auto;
    background: #f7ffff;
    max-width: 300px;
    scrollbar-width: none;  /* Firefox */
    -ms-overflow-style: none;  /* IE/Edge */
}

.toc::-webkit-scrollbar {
    display: none;
}

pre, pre code{

    white-space: pre-wrap !important;      /* 允许在空白符处换行 */
    word-wrap: break-word !important;      /* 允许长单词或 URL 换行 */
    overflow-wrap: break-word !important;  /* 同上,现代浏览器支持 */
    overflow: visible;          /* 禁止滚动条 */
    max-width: 100%;            /* 限制最大宽度 */
    background: #f5f5f5;        /* 可选:背景色 */
    box-sizing: border-box;
    min-width: 0;
}


h2:after {
    content: '';
    width: 70%;
    display: block;
    margin: .2em auto 0;
    /* border-bottom: 2px solid var(--primary-colour); */
}

h3 {
    /* padding-right: 2px solid var(--primary-colour); */
    /* border-left: 2px solid var(--primary-colour); */
    /* background: #f6f8fa; */
    color: #306797 !important;
}

li::marker {
    color: #306797;
}

blockquote {
    padding-left: 16px;
    border-left: 1px solid #6c757d;
    color: #6c757d;
}

#mainBox{
    max-width:100% !important;
}

.article-aside-container{
    left:1576px !important
}
    `;
    const styleElement = document.createElement('style');
    styleElement.textContent = cssContent;
    const head = document.getElementsByTagName('head')[0];
    head.appendChild(styleElement);
  }

  catelog();
  addCss();
  clean_vip();
  clean_follow();
  document.addEventListener('DOMContentLoaded', function () {
    addCss();
    catelog();
    clean_vip();
    clean_follow();
  });

  window.addEventListener('load', function () {
    addCss();
    catelog();
    clean_vip();
    clean_follow();
  });

})();

搜索页美化

美化前:
在这里插入图片描述美化后:
在这里插入图片描述

代码:

// ==UserScript==
// @name         0【自写】csdn搜索页美化
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  对于https://so.csdn.net/so/search前缀网址,若不含t=blog则添加t=blog&后重新访问
// @author       Ji
// @match        https://so.csdn.net/so/*
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  function reset_url() {
    // 重置URL
    var currentUrl = window.location.href;
    console.log(currentUrl);
    const base = "https://so.csdn.net/so/search";
    if (currentUrl.indexOf('t=blog') === -1) {
      let parts = currentUrl.split('&');
      let resultParts = [];
      for (let part of parts) {
        if (!part.startsWith('t=')) {
          resultParts.push(part);
        }
      }
      const newUrl = resultParts.join('&') + "&t=blog";
      console.log("newUrl", newUrl);
      window.location.href = newUrl;
    }

  }

  function clean_rabbish() {
    const selectors = [
        '.chat-inline-content',
        '.s-nav',
        '#csdn-toolbar',
        '.main-rt',
        '#ai-search-frame-main'
    ];

    function removeElement(selector) {
        const elements = document.querySelectorAll(selector);
        elements.forEach(el => {
            if (el && el.parentNode) {
                el.parentNode.removeChild(el);
            }
        });
    }

    // 删除包含'.vip-tag'的'.list-item'元素
    function removeVipItems() {
        const listItems = document.querySelectorAll('.list-item');
        listItems.forEach(item => {
            const vipTag = item.querySelector('.vip-tag');
            if (vipTag) {
                item.parentNode.removeChild(item);
            }
        });
    }

    // 立即执行一次清理
    selectors.forEach(removeElement);
    removeVipItems();

    // 创建一个 MutationObserver,监听 DOM 变化
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(() => {
            // 每次 DOM 变化都尝试删除目标元素
            removeElement('#ai-search-frame-main');
            // 同时检查并删除VIP项目
            removeVipItems();
        });
    });

    // 开始监听 document.body 及其子节点的变动(包括新增节点)
    observer.observe(document.body, {
        childList: true,        // 监听子节点增减
        subtree: true,          // 监听所有后代节点
        attributes: false,      // 不监听属性变化(可选)
    });

    // 暴露 observer 以便后续手动断开(可选)
    window._csdnCleanupObserver = observer;
}


  function addCss() {
    const cssContent = `
body{
  background:none !important;
}
.so-items-normal{
  border:1px solid gray;
  border-radius:5px;
  margin-bottom:5px;
  background-color:#e8e8e8 !important;
}
.so-list-detail .main
{
  padding-top:0 !important;
}
  `;
    const styleElement = document.createElement('style');
    styleElement.textContent = cssContent;
    const head = document.getElementsByTagName('head')[0];
    head.appendChild(styleElement);
  }



  reset_url();
  clean_rabbish();
  addCss();

  document.addEventListener('DOMContentLoaded', function () {
    clean_rabbish();
    addCss();
  });

  window.addEventListener('load', function () {
    clean_rabbish();
    beauty();
    setTimeout(() => {
      clean_rabbish();
      addCss()
    }, 1000);
  });

})();

CSDN字体更改

效果:

代码:

// ==UserScript==
// @name         0【自写】csdn改字体
// @namespace    http://tampermonkey.net/
// @version      2025-09-12
// @description  改字体
// @author       Ji
// @match        https://blog.csdn.net/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=csdn.net
// @grant        none
// ==/UserScript==

(function () {
    'use strict';


    function setupFontSwitcher() {
        // 字体配置
        const chineseFonts = [
            { name: 'Noto Serif SC', title: '思源宋体' },
            { name: 'Noto Sans SC', title: '思源黑体' },
            { name: 'SimSun', title: '宋体' },
            { name: 'Microsoft YaHei', title: '微软雅黑' }
        ];

        const englishFonts = [
            { name: 'Nunito', title: 'Nunito' },
            { name: 'Roboto', title: 'Roboto' },
            { name: 'Open Sans', title: 'Open Sans' },
            { name: 'Inter', title: 'Inter' },
            { name: 'Poppins', title: 'Poppins' },
            { name: 'Arial', title: 'Arial' }
        ];

        const monospaceFonts = [
            { name: 'Source Code Pro', title: 'Source Code Pro' },
            { name: 'Fira Code', title: 'Fira Code' },
            { name: 'JetBrains Mono', title: 'JetBrains Mono' },
            { name: 'Courier New', title: 'Courier New' }
        ];

        // 默认字体
        let currentChineseFont = chineseFonts[0];
        let currentEnglishFont = englishFonts[0];
        let currentMonospaceFont = monospaceFonts[2]; // JetBrains Mono

        // 创建字体链接
        const fontLink = document.createElement('link');
        fontLink.href = 'https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@300;400;600&family=Noto+Sans+SC:wght@300;400;500;700&family=Nunito:wght@300;400;600;700&family=Roboto:wght@300;400;700&family=Open+Sans:wght@300;400;600&family=Inter:wght@300;400;500;600;700&family=Poppins:wght@300;400;500;600&family=Source+Code+Pro:wght@300;400;600&family=Fira+Code:wght@300;400;600&family=JetBrains+Mono:wght@300;400;600&display=swap';
        fontLink.rel = 'stylesheet';
        document.head.appendChild(fontLink);

        // 创建字体样式
        const style = document.createElement('style');
        style.id = 'font-switcher-styles';
        document.head.appendChild(style);

        // 应用字体
        function applyFonts() {
            style.textContent = `
            body, div, p, h1, h2, h3, h4, h5, h6, span, a, li, td, th, input, textarea, button {
                font-family: "${currentEnglishFont.name}", "${currentChineseFont.name}", sans-serif !important;
            }

            code, pre, .code, .monospace, [class*="code"], [class*="mono"] {
                font-family: "${currentMonospaceFont.name}", monospace !important;
            }
        `;

            // 保存到localStorage
            try {
                localStorage.setItem('fontConfig', JSON.stringify({
                    chinese: currentChineseFont.name,
                    english: currentEnglishFont.name,
                    monospace: currentMonospaceFont.name
                }));
            } catch (e) {
                console.log('无法保存字体设置');
            }
        }

        // 从localStorage加载设置
        function loadFontSettings() {
            try {
                const saved = localStorage.getItem('fontConfig');
                if (saved) {
                    const config = JSON.parse(saved);

                    const chinese = chineseFonts.find(f => f.name === config.chinese);
                    const english = englishFonts.find(f => f.name === config.english);
                    const monospace = monospaceFonts.find(f => f.name === config.monospace);

                    if (chinese) currentChineseFont = chinese;
                    if (english) currentEnglishFont = english;
                    if (monospace) currentMonospaceFont = monospace;
                }
            } catch (e) {
                console.log('无法加载字体设置');
            }
            applyFonts();
        }

        // 创建字体选择UI
        function createFontSelector() {
            const selector = document.createElement('div');
            selector.id = 'font-selector';
            selector.style.cssText = `
            position: fixed;
            top: 120px;
            right: 20px;
            z-index: 10000;
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            width: 280px;
            max-height: 70vh;
            overflow-y: auto;
            font-family: 'Nunito', 'Noto Sans SC', sans-serif;
            display: none;
        `;

            // 标题
            const title = document.createElement('h3');
            title.textContent = '字体设置';
            title.style.cssText = 'margin: 0 0 20px 0; font-size: 18px; color: #2c3e50; text-align: center;';
            selector.appendChild(title);

            // 创建字体选择组
            function createFontGroup(fonts, currentFont, type, title) {
                const group = document.createElement('div');
                group.style.marginBottom = '20px';

                const heading = document.createElement('h4');
                heading.textContent = title;
                heading.style.cssText = 'margin: 0 0 12px 0; font-size: 14px; color: #4b6cb7;';
                group.appendChild(heading);

                const container = document.createElement('div');
                container.style.display = 'grid';
                container.style.gridTemplateColumns = 'repeat(2, 1fr)';
                container.style.gap = '8px';

                fonts.forEach(font => {
                    const btn = document.createElement('button');
                    btn.textContent = font.title;
                    btn.style.cssText = `
                    padding: 8px 12px;
                    border: 1px solid #ddd;
                    border-radius: 6px;
                    background: ${font.name === currentFont.name ? '#4b6cb7' : '#f8f9fa'};
                    color: ${font.name === currentFont.name ? 'white' : '#333'};
                    cursor: pointer;
                    font-size: 12px;
                    transition: all 0.2s;
                `;

                    btn.addEventListener('click', () => {
                        if (type === 'chinese') {
                            currentChineseFont = font;
                        } else if (type === 'english') {
                            currentEnglishFont = font;
                        } else if (type === 'monospace') {
                            currentMonospaceFont = font;
                        }
                        applyFonts();
                        updateSelectorUI();
                    });

                    container.appendChild(btn);
                });

                group.appendChild(container);
                return group;
            }

            // 添加字体选择组
            selector.appendChild(createFontGroup(chineseFonts, currentChineseFont, 'chinese', '中文字体'));
            selector.appendChild(createFontGroup(englishFonts, currentEnglishFont, 'english', '英文字体'));
            selector.appendChild(createFontGroup(monospaceFonts, currentMonospaceFont, 'monospace', '代码字体'));

            // 关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.textContent = '关闭';
            closeBtn.style.cssText = `
            width: 100%;
            padding: 10px;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            margin-top: 10px;
        `;
            closeBtn.addEventListener('click', () => {
                selector.style.display = 'none';
            });
            selector.appendChild(closeBtn);

            document.body.appendChild(selector);
            return selector;
        }

        // 更新选择器UI
        function updateSelectorUI() {
            const selector = document.getElementById('font-selector');
            if (!selector) return;

            selector.querySelectorAll('button').forEach(btn => {
                const fontName = btn.textContent;

                // 重置所有按钮样式
                btn.style.background = '#f8f9fa';
                btn.style.color = '#333';
                btn.style.borderColor = '#ddd';

                // 检查是否是当前选中的字体
                if (
                    (chineseFonts.some(f => f.title === fontName && f.name === currentChineseFont.name) ||
                        englishFonts.some(f => f.title === fontName && f.name === currentEnglishFont.name) ||
                        monospaceFonts.some(f => f.title === fontName && f.name === currentMonospaceFont.name))
                ) {
                    btn.style.background = '#4b6cb7';
                    btn.style.color = 'white';
                    btn.style.borderColor = '#4b6cb7';
                }
            });
        }

        // 创建切换按钮
        function createToggleButton() {
            const btn = document.createElement('button');
            btn.textContent = '字体';
            btn.title = '切换字体';
            btn.id = 'font-toggle-btn';
            btn.style.cssText = `
            position: fixed;
            top: 120px;
            right: 20px;
            z-index: 9999;
            background: #4b6cb7;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            font-family: 'Nunito', sans-serif;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s;
        `;

            btn.addEventListener('mouseenter', () => {
                btn.style.transform = 'scale(1.1)';
                btn.style.background = '#3b5998';
            });

            btn.addEventListener('mouseleave', () => {
                btn.style.transform = 'scale(1)';
                btn.style.background = '#4b6cb7';
            });

            return btn;
        }

        // 初始化
        function init() {
            loadFontSettings();

            const toggleBtn = createToggleButton();
            const selector = createFontSelector();

            toggleBtn.addEventListener('click', () => {
                selector.style.display = selector.style.display === 'none' ? 'block' : 'block';
                updateSelectorUI();
            });

            document.body.appendChild(toggleBtn);

            // 点击外部关闭选择器
            document.addEventListener('click', (e) => {
                const selector = document.getElementById('font-selector');
                const toggleBtn = document.getElementById('font-toggle-btn');

                if (selector && selector.style.display === 'block' &&
                    !selector.contains(e.target) &&
                    e.target !== toggleBtn) {
                    selector.style.display = 'none';
                }
            });
        }

        // 启动
        init();
    }

    // 执行函数
    setupFontSwitcher();
})();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值