首页 > 解决方案 > Jquery 编辑 css 字体系列值

问题描述

我正在尝试编写一个用户脚本,如果它们属于用户定义的列表,例如 ['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等。所以我也想编辑这些变量的值。

标签: jquerycsstampermonkeyuserscripts

解决方案


  • 在您的情况下,使用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>


推荐阅读