通过元素 ID 获取所有样式属性
您可以通过使用以下方法提供元素 ID 来获取应用于元素的所有样式属性:
循环遍历 CSSStyleDeclaration 对象:
迭代 CSSStyleDeclaration 对象 (getCompulatedStyle) 的索引以获取每个已知的属性名称。使用带有此名称的 getPropertyValue 来检索值。
处理内联样式:
对于内联样式,请使用与其他样式类型相同的循环方法。
将它们放在一起:
这是代码:
<code class="javascript">function getStyleById(id) { return getAllStyles(document.getElementById(id)); } function getAllStyles(elem) { if (!elem) return []; var win = document.defaultView || window, style, styleNode = []; if (win.getComputedStyle) { /* Modern browsers */ style = win.getComputedStyle(elem, ''); for (var i=0; i<style.length i stylenode.push style style.getpropertyvalue else if ie for name in ancient browser.. return stylenode></style.length></code>
以上是如何在 JavaScript 中通过 ID 检索元素的所有样式属性?的详细内容。更多信息请关注PHP中文网其他相关文章!