Get the computed style and omit defaults

前端 未结 6 853
旧巷少年郎
旧巷少年郎 2020-12-28 19:57

I\'m trying to get the current runtime style of an element and filter out properties that have default values. For example, with markup like this:



        
6条回答
  •  伪装坚强ぢ
    2020-12-28 20:21

    Here it is .. using pure javscript .. I only added jquery to the fiddle to set document.ready event.

    Here is the code:

    $(document).ready(function () {
        var div = document.getElementById('output');
        var x = document.getElementById('frame').contentWindow.document.createElement('x');
        document.getElementById('frame').contentWindow.document.body.appendChild(x);
        var defautlStyles = window.getComputedStyle(x);
        var barStyles = window.getComputedStyle(document.getElementById('bar'));
        for (i = 0; i < defautlStyles.length; i++) {
            if (defautlStyles["" + defautlStyles[i]] != barStyles["" + barStyles[i]]) {
                var p = document.createElement('p');
                p.innerText += barStyles[i] + ": " + barStyles["" + barStyles[i]];
                div.appendChild(p);
            }
        }
    });
    

    I used an iframe to add an element to it so the style of the added element won't be affected by the document default styles. And here is the FIDDLE

    Hope it helps...

提交回复
热议问题