2017-09-26 61 views
1

我正在使用以下函数来获取某个computedStyle的所有HTML元素。例如getCssByRule('margin-left')将生成一个数组,其中包含页面中所有具有空白余量的元素。如何从HTML元素中提取计算的样式值?

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

如何修改这个函数,这样我也可以得到这个computedValue的值? (例如30px)?

回答

3

如果你想获得的计算值的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>

1

我倒是第一次地图上的元素,然后用它们进行过滤你的规则。这样你只需要getComputedStyle一次。下面将返回对象的数组与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>

+1

该死,你是快,几秒打我;) – Terry

相关问题