JavaScript get Styles

偶尔善良 提交于 2019-11-27 05:11:58

You are talking about what is known as Computed Style, check out these article on how to get it:

From the last article, here is a function:

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

How to use it:

CSS:

/* Element CSS*/
div#container{
    font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
}

JS:

var elementFontSize = getStyle(document.getElementById("container"), "font-size");
Ajain Vivek

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   

You might use:

var ob = document.getElementById("myLayer");
var pos = ob.style.position;

Every CSS property has it's own object model. Usually those css properties that contain '-' are written using java model.

For example:

//getting background-color property
var ob = document.getElementById("myLayer");
var color = ob.style.backgroundColor;

If you want to get all the css properties that are defined for an object, you will have to list them one by one, because even if you did not set the property in your style sheet, an object will have it with the default value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!