Greasy Fork

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

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

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

// ==UserScript==
// @name         调整网页字体和行间距倍数
// @author       ChatGPT
// @version      6.6
// @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);

  function applyStyles() {
    // 当字体和行间距倍数都为1时,尝试移除已有的<style>元素并退出函数
    if (fontMultiplier === 1 && lineHeightMultiplier === 1) {
      var existingStyleElement = document.getElementById('customFontAndLineHeightStyle');
      if (existingStyleElement) {
        existingStyleElement.remove();
      }
      return; // 不需要应用任何样式,直接退出
    }

    var styleElement = document.getElementById('customFontAndLineHeightStyle');
    if (!styleElement) {
      styleElement = document.createElement('style');
      styleElement.id = 'customFontAndLineHeightStyle';
      document.head.appendChild(styleElement);
    }

    styleElement.innerHTML = `
      :root, body, *{
        font-size: ${100 * fontMultiplier}% !important;
        line-height: ${100 * lineHeightMultiplier}% !important;
      }
    `;
  }

  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("请输入有效的数字");
    }
  });
})();