使用 JavaScript 提取 CSS 属性
浏览附加到 HTML 文档的样式表可以为页面元素的表示提供有价值的见解。特别是,读取特定 CSS 属性的能力可以帮助动态样式操作。
一种方法涉及手动检查 document.styleSheets 对象并解析样式规则。然而,这种方法是劳动密集型的,并且可能变得笨拙,特别是在针对特定选择器时。
更直接的技术是创建一个与所需选择器匹配的临时元素。使用 getCompulatedStyle()(对于现代浏览器)或 currentStyle(对于 Internet Explorer)方法,您可以检索所创建元素的任何 CSS 属性的计算值。
例如,考虑以下代码来检索具有“layout”类的
function getStyleProp(elem, prop) {
if (window.getComputedStyle) {
return window.getComputedStyle(elem, null).getPropertyValue(prop);
} else if (elem.currentStyle) {
return elem.currentStyle[prop]; // IE
}
}
window.onload = function () {
var d = document.createElement("div"); // Create div
d.className = "layout"; // Set class = "layout"
alert(getStyleProp(d, "color")); // Get property value
};
或者,如果您想确定从样式表继承的 CSS 属性而不考虑任何内联样式,可以使用以下函数:
function getNonInlineStyle(elem, prop) {
var style = elem.cssText; // Cache the inline style
elem.cssText = ""; // Remove all inline styles
var inheritedPropValue = getStyleProp(elem, prop); // Get inherited value
elem.cssText = style; // Add the inline style back
return inheritedPropValue;
}
通过利用这些技术,开发人员可以动态调整元素的 CSS 属性、操作其呈现方式,并更深入地了解页面的样式。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3