Greasy Fork

调整网页字体和行间距倍数

脚本菜单可用于调整网页的字体和行间距倍数

当前为 2024-03-03 提交的版本,查看 最新版本

// ==UserScript==
// @name         调整网页字体和行间距倍数
// @author       ChatGPT
// @version      6.4
// @description  脚本菜单可用于调整网页的字体和行间距倍数
// @match        *://*/*
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// @run-at       document-end
// @namespace https://greasyfork.org/users/452911
// ==/UserScript==

(function () {
  "use strict";

  var storageKey = window.location.hostname;
  var fontMultiplier = GM_getValue(storageKey + "_font_multiplier", 1);
  var lineHeightMultiplier = GM_getValue(storageKey + "_line_height_multiplier", 1);
  var originalStyles = {};

  function recordOriginalStyles() {
    const root = document.documentElement;
    originalStyles['root'] = {
      fontSize: parseFloat(getComputedStyle(root).fontSize),
      lineHeight: parseFloat(getComputedStyle(root).lineHeight) || parseFloat(getComputedStyle(root).fontSize) * 1.2
    };

    document.querySelectorAll('*').forEach((element, index) => {
      const elementStyle = getComputedStyle(element);
      originalStyles[`element${index}`] = {
        fontSize: parseFloat(elementStyle.fontSize),
        lineHeight: parseFloat(elementStyle.lineHeight) || parseFloat(elementStyle.fontSize) * 1.2
      };
    });
  }

  function applyStyles() {
    if (Object.keys(originalStyles).length === 0) {
      recordOriginalStyles();
    }

    const rootStyle = originalStyles['root'];
    document.documentElement.style.fontSize = `${rootStyle.fontSize * fontMultiplier}px`;
    document.documentElement.style.lineHeight = `${rootStyle.lineHeight * lineHeightMultiplier}px`;

    document.querySelectorAll('*').forEach((element, index) => {
      const style = originalStyles[`element${index}`];
      if (style) {
        element.style.fontSize = `${style.fontSize * fontMultiplier}px`;
        element.style.lineHeight = `${style.lineHeight * lineHeightMultiplier}px`;
      }
    });
  }

  applyStyles();

  GM_registerMenuCommand("调整字体大小", function () {
    var newFontMultiplier = prompt("请输入字体大小倍数", fontMultiplier.toString());
    if (newFontMultiplier !== null && !isNaN(newFontMultiplier)) {
      fontMultiplier = parseFloat(newFontMultiplier);
      GM_setValue(storageKey + "_font_multiplier", fontMultiplier);
      applyStyles();
    } else {
      alert("请输入有效的数字");
    }
  });

  GM_registerMenuCommand("调整行间距", function () {
    var newLineHeightMultiplier = prompt("请输入行间距倍数", lineHeightMultiplier.toString());
    if (newLineHeightMultiplier !== null && !isNaN(newLineHeightMultiplier)) {
      lineHeightMultiplier = parseFloat(newLineHeightMultiplier);
      GM_setValue(storageKey + "_line_height_multiplier", lineHeightMultiplier);
      applyStyles();
    } else {
      alert("请输入有效的数字");
    }
  });
})();