Get the computed style and omit defaults

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

    You can use, e.g:

    window.getComputedStyle(document.getElementById('bar'))
    

    This will return an object containing all the computed styles for the element with the id 'bar'.

    So, for example you could do:

    var styles = window.getComputedStyle(document.getElementById('bar'));
    styles = "background-color:" + styles['background-color'] + ";color:" + styles['color'] + ";font-size:" + styles['font-size'] + ";";
    console.log(styles);
    

    Note that color values will be returned in RGBA format.

    Demo Fiddle

提交回复
热议问题