【发布时间】:2018-04-04 06:27:52
【问题描述】:
我正在使用github 上的这个 JS 脚本来检测网页中使用的字体:
function styleInPage(css, verbose) {
// polyfill getComputedStyle
if (typeof getComputedStyle == "undefined") {
getComputedStyle = function (elem) {
return elem.currentStyle;
}
}
// set vars
var style,
thisNode,
styleId,
allStyles = [],
nodes = document.body.getElementsByTagName('*');
// loop over all elements
for (var i = 0; i < nodes.length; i++) {
thisNode = nodes[i];
if (thisNode.style) {
styleId = '#' + (thisNode.id || thisNode.nodeName + '(' + i + ')');
style = thisNode.style.fontFamily || getComputedStyle(thisNode, '')[css];
// get element’s style
if (style) {
if (verbose) {
allStyles.push([styleId, style]);
} else if (allStyles.indexOf(style) == -1) {
allStyles.push(style);
}
// add data-attribute with key for allStyles array
thisNode.dataset.styleId = allStyles.indexOf(style);
}
// get element:before’s style
styleBefore = getComputedStyle(thisNode, ':before')[css];
if (styleBefore) {
if (verbose) {
allStyles.push([styleId, styleBefore]);
} else if (allStyles.indexOf(styleBefore) == -1) {
allStyles.push(styleBefore);
}
// add data-attribute with key for allStyles array
thisNode.dataset.styleId = allStyles.indexOf(styleBefore);
}
// get element:after’s style
styleAfter = getComputedStyle(thisNode, ':after')[css];
if (styleAfter) {
if (verbose) {
allStyles.push([styleId, styleAfter]);
} else if (allStyles.indexOf(styleAfter) == -1) {
allStyles.push(styleAfter);
}
// add data-attribute with key for allStyles array
thisNode.dataset.styleId = allStyles.indexOf(styleAfter);
}
}
}
return allStyles;
}
问题是,如果我使用getComputedStyle,我确实得到了样式,比如我是否在寻找字体系列,但我没有得到渲染字体的确切名称。而如果我在 Chrome 中检查 DevTools,我可以看到确切字体的实际名称。
例如。如果您将此脚本用于https://carpentercollective.com/ 等网站
我得到使用的字体是serif1,但渲染的字体实际上被称为Grifo
如何使用 JS 获取该信息?
【问题讨论】:
标签: javascript html css google-chrome fonts