JavaScript get Styles

前端 未结 3 1947
心在旅途
心在旅途 2020-11-30 12:12

Is it possible to get ALL of the styles for an object using JavaScript? Something like:


main.css
-------
#myLayer {
  position: absolute;
  width: 200px;
          


        
3条回答
  •  误落风尘
    2020-11-30 12:19

    Polyfill to get the current CSS style of element using javascript ... Visit the link for more info

    /**
    * @desc : polyfill for getting the current CSS style of the element
    * @param : elem - The Element for which to get the computed style.
    * @param : prop - The Property for which to get the value
    * @returns : The returned style value of the element
    **/
    var getCurrentStyle = function (ele, prop) {
    
    var currStyle;
    if (!window.getComputedStyle) {
        currStyle = ele.currentStyle[prop];
    } else {
        currStyle = window.getComputedStyle(ele).getPropertyValue(prop);
    }
    
    return currStyle;
    }
    
    
    /** How to use **/
    var element = document.getElementById("myElement");
    getCurrentStyle(element, "width"); // returns the width value   
    

提交回复
热议问题