【问题标题】:Jquery to edit css font-family valuesJquery 编辑 css 字体系列值
【发布时间】:2021-12-09 08:32:42
【问题描述】:

我正在尝试编写一个用户脚本,如果它们属于用户定义的列表,例如 ['arial', 'verdana', 'open sans'],则从 font-family 中删除这些值。

原文:font-family: Arial, Verdana, "Segoe UI", sans-serif;

修改:font-family: "Segoe UI", sans-serif;

使用 jquery,有没有一种有效的方法来删除一些匹配的值,或者我必须在每个属性上使用带有正则表达式的 replace() 方法?

此外,一些网站将字体系列值存储在其他一些变量中,例如 --ff-sans--ff-serif 等。所以我也想编辑这些变量的值。

【问题讨论】:

  • 也可以使用jQuery重新定义font-family的属性值
  • 你要问的是查询整个 DOM,每个元素,一个一个,检查它的 window.getComputedStyle(Node) 并解析 font-family 等的条目等等......为什么,首先,你想做你想要的?有什么具体原因吗?你的用例是什么?有什么代码可以显示吗?有关您正在构建的内容的更多详细信息吗?
  • @Roko 我在 Firefox usercss 中使用 @font-face {font-family: 'Arial'; src: local('sans-serif');} 来替换丑陋的 Windows 字体。这在 Chrome(使用手写笔)中不起作用。我试图使用 Tampermonkey 获得类似的结果。我对 jquery 不是很熟悉,但它似乎是最好的方法。

标签: jquery css tampermonkey userscripts


【解决方案1】:
  • 使用 getComputedStyle 及其getPropertyValue 方法获取您的案例中的当前样式(“font-family”)
  • 使用querySelectorAll() 获得与提供的选择器匹配的所需元素(我使用"body *:not(script):not(style)"

// Utility functions
const ELS = (sel, EL) => (EL || document).querySelectorAll(sel);
const getStyle = (EL, prop) => getComputedStyle(EL, null).getPropertyValue(prop);
const matchesSome = (str, arr) => arr.some(x => str.toLowerCase().includes(x.toLowerCase()));


// Define your array of desides matches and replacement:
const fontFamilyMatches = ["arial", "verdana", "open sans"];
const fontFamilyReplace = `"Segoe UI", sans-serif`;

// Get all elelemts inside body
const ELS_all = ELS("body *:not(script):not(style)");

// Replace fonts that match one in the fontFamilyMatches Array
// with the one defined in fontFamilyReplace
ELS_all.forEach(EL => {
  const fontFamily = getStyle(EL, "font-family");

  if (matchesSome(fontFamily, fontFamilyMatches)) {
    EL.style.fontFamily = fontFamilyReplace
  }
});
h1,
h2 {
  font-family: "Open Sans", sans-serif;
}

p {
  font-family: Arial, Verdana, "Segoe UI", sans-serif;
}

blockquote {
  font-family: 'Bookman Old Style', serif;
}

span {
  font-family: Verdana, Geneva, sans-serif;
}
<h1>Lorem ipsum</h1>

<div>
  Lorem ipsum dolor sit amet.
  <p>
    Consectetur adipisicing elit.<br> In reiciendis delectus saepe hic.
  </p>
</div>

<p>
  <span>tempora tempore recusandae molestiae!</span> atque sint dolor a! Id quae rem consequatur deleniti autem, <span>aliquid consectetur</span> adipisicing elit. Dicta iusto corporis dolor.
</p>

<h2>Dolor sit amet</h2>

<p>
  ullam eius dignissimos sequi ut.
</p>

<blockquote>
  Lorem ipsum dolor sit amet
</blockquote>

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多