Get the computed style and omit defaults

前端 未结 6 870
旧巷少年郎
旧巷少年郎 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:24

    Here's a more robust solution to this, using an iframe. This solution is inefficient for more than one element at a time, in which case you'll want to use a fragment to batch element insertion and pass in an array of tag names.

    var getDefaultStyling = function(tagName){
        if(!tagName) tagName = "dummy-tag-name";
    
        //  Create dummy iframe
    
        var iframe = document.createElement("iframe");
    
        document.body.appendChild(iframe);
    
        //  Create element within the iframe's document
    
        var iframeDocument = iframe.contentDocument;
        var targetElement = iframeDocument.createElement(tagName);
    
        iframeDocument.body.appendChild(targetElement);
    
        //  Grab styling (CSSStyleDeclaration is live, and all values become "" after element removal)
    
        var styling = iframe.contentWindow.getComputedStyle(targetElement);
        var clonedStyling = {};
    
        for(var i = 0, len = styling.length; i < len; i++){
            var property = styling[i];
    
            clonedStyling[i] = property;
            clonedStyling[property] = styling[property];
        }
    
        //  Remove iframe
    
        document.body.removeChild(iframe);
    
        //  Return cloned styling
    
        return clonedStyling;
    };
    
    var getUniqueUserStyling = function(element){
        var allStyling = window.getComputedStyle(element);
        var defaultStyling = getDefaultStyling(element.tagName);
    
        var userStyling = {};
    
        for(var i = 0, len = allStyling.length; i < len; i++){
            var property = allStyling[i];
            var value = allStyling[property];
            var defaultValue = defaultStyling[property];
    
            if(value != defaultValue){
                userStyling[property] = value;
            }
        }
    
        return userStyling;
    };
    

    Usage: getUniqueUserStyling(myElement).

提交回复
热议问题