2017-09-26 15 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

関連する問題