在没有 CSS 定义的情况下访问渲染字体
在检查 HTML 元素的属性时,很明显重要信息当使用 JavaScript 的 object.style 属性时,像 font-face 和 font-size 一样丢失。这是因为元素的样式是从网页的 CSS 继承的,并且在显式定义这些属性之前,object.style 属性保持为空。
但是,仍然可以使用以下方式检索实际渲染的字体信息getCompatedStyle 方法。这是一个完成此操作的 JavaScript 函数:
function css(element, property) { return window.getComputedStyle(element, null).getPropertyValue(property); }
要使用此函数,只需传入您要检查的元素和要检索的属性,例如“font-size”。例如:
css(object, 'font-size'); // Returns '16px' or similar
需要注意的是,Internet Explorer 8 不支持此方法。
现场演示:
点击此处在 JSFiddle 上观看现场演示: http://jsfiddle.net/4mxzE/
代码片段:
// Retrieve the computed style information console.log( getComputedStyle(document.getElementById('test'), null) .getPropertyValue('font') ); // Define a custom CSS style for the element document.getElementById('test').style.cssText = 'font-family: fantasy, cursive;'; // Append an HTML element to the document document.body.appendChild(document.getElementById('test'));
#test { /* Custom font-face applied */ }
<!-- Element with rendered font --> <div>
以上是当 CSS 定义不存在时,如何在 JavaScript 中访问渲染的字体信息?的详细内容。更多信息请关注PHP中文网其他相关文章!