简体   繁体   English

如何从HTML元素中提取计算出的样式值?

[英]How to extract computed style values from HTML elements?

I'm using the following function to get all the HTML elements with a certain computedStyle. 我正在使用以下函数来获取具有特定computeStyle的所有HTML元素。 FOr example getCssByRule('margin-left') will produce an array with all the elements in the page that have margin left. 例如,示例getCssByRule('margin-left')将产生一个数组,其中包含页面中所有具有空白的元素。

getCssByRule (rule) {
  const elements = Array.from(document.querySelectorAll('*')).filter(e => {
    return parseInt(window.getComputedStyle(e).getPropertyValue(rule)) !== 0
  })
  return elements
}

How to modify this function so I can also get the value of this computedValue? 如何修改此函数,以便我也可以获取此computeValue的值? (eg 30px )? (例如30px )?

If you want to get an Array of computed values, then you can modify your function like this: 如果要获取计算值Array ,则可以像下面这样修改函数:

 function getCssByRule(rule) { const values = Array.from(document.querySelectorAll('*')) .filter(e => parseInt(window.getComputedStyle(e).getPropertyValue(rule)) !== 0) .map(e => window.getComputedStyle(e).getPropertyValue(rule)); return values; } console.log(getCssByRule('margin-left')); 
 <div style="margin-left: 20px"></div> <div style="margin-left: 19px"></div> <div></div> <div style="margin-left: 18px"></div> 

I'd first map over the elements, then filter them using your rule. 我首先会在元素上进行映射,然后使用您的规则对其进行过滤。 That way you'll need to getComputedStyle only once. 这样,您只需要一次getComputedStyle Below will return an array of objects with element => value pairs 下面将返回一个带有element => value对的对象数组

 function getCssByRule(rule) { return Array.from(document.querySelectorAll('*')).map(element => ({ element, value: window.getComputedStyle(element).getPropertyValue(rule) }) ).filter(e => parseInt(e.value) !== 0); } console.log(getCssByRule('margin-left')); 
 <div> Foo </div> <div id="foo" style="margin-left:10px"> Bar </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM