jquery - 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
等。所以我也想编辑这些变量的值。
解决方案
- 在您的情况下,使用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>
推荐阅读
- java - 在 Java 中使用简单的嵌套循环实现内连接
- java - 如何处理动态变量号。java中的参数?
- javascript - 如何修复“TypeError:_this 未定义”
- python - 使用 geopy.distance 进行批量计算
- django - django - 将文件上传到特定文件夹
- javascript - 获取在没有 ID 的 Anchor 标记中写入的文本:javascript
- python - tensorflow 中的 tf.GraphKeys.GLOBAL_VARIABLES 和 tf.GraphKeys.TRAINABLE_VARIABLES 有什么区别?
- python - 编写一个 if 条件来过滤记录,使用日期来获取数据过滤器
- django - 如何用 ForeignKey 关系显示多个字段的值?
- mysql - 在 SQL 中将行转置为列