JSFiddle - React, Tailwind, and code Playground
HTML
<h1 class="title">面朝大海,春暖花开</h1>
<pre id="log"></pre>
CSS
@font-face {
font-family: 'demo-font';
src: url('./demo-font.ttf');
}
h1.title {
font-family: 'demo-font';
}
h1.title::after {
content: '——海子';
}
JavaScript
// 遍历 CSS 的规则
var eachCssRuleList = (function() {
// 遍历 CSSRuleList
function cssRuleListFor(cssRuleList, callback) {
var index = -1;
var length = cssRuleList.length;
var cssRule, cssStyleSheet;
while (++index < length) {
cssRule = cssRuleList[index];
// 导入的样式规则
if (cssRule instanceof CSSImportRule) {
cssStyleSheet = cssRule.styleSheet;
cssRuleListFor(cssStyleSheet.cssRules || [], callback);
// CSS 媒体查询规则
} else if (cssRule instanceof CSSMediaRule) {
cssRuleListFor(cssRule.cssRules || [], callback);
// 普通的规则
} else {
callback(cssRule);
}
}
}
return function(callback) {
var index = -1;
var styleSheetList = document.styleSheets;
var length = styleSheetList.length;
var cssStyleSheet, cssRuleList;
// 遍历 StyleSheetList
while (++index < length) {
cssStyleSheet = styleSheetList[index];
cssRuleList = cssStyleSheet.cssRules || [];
cssRuleListFor(cssRuleList, callback);
}
};
})();
// 字体信息
var webFonts = {};
// 字体对应的元素列表
var elements = {};
// 找到 fontFace
eachCssRuleList(function(cssRule) {
if (cssRule instanceof CSSFontFaceRule) {
var style = cssRule.style;
var family = style['font-family'];
var src = style.src;
// 保存使用此字体的所有元素列表
elements[family] = [];
// 保存字体信息
webFonts[family] = {
family: family,
src: src,
chars: ''
};
}
});
// 获取当前节点所使用的 fontFace
function matchFontFamily(cssRule) {
var style = cssRule.style;
var family = style['font-family'];
return webFonts[family];
}
// 将 fontFace 与元素、字符关联起来
eachCssRuleList(function(cssRule) {
if (cssRule instanceof CSSStyleRule) {
var selector = cssRule.selectorText;
var webfont =...