【问题标题】:JavaScript get StylesJavaScript 获取样式
【发布时间】:2011-05-09 13:00:50
【问题描述】:

是否可以使用 JavaScript 获取对象的所有样式?比如:

main.css ------- #myLayer { position: absolute; width: 200px; height: 100px; color: #0000ff; } main.js ------- var ob = document.getElementById("myLayer"); var pos = ob.(getPosition); // Pos should equal "absolute" but // ob.style.position would equal null // any way to get absolute?

【问题讨论】:

  • 我就是不明白。 main.js 应该怎么做?
  • 你的意思是自定义css定义的所有样式吗?

标签: javascript css styling


【解决方案1】:

您说的是所谓的Computed Style,请查看以下文章了解如何获得它:

从上一篇文章,这里有一个函数:

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;
}

如何使用:

CSS:

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

JS:

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

【讨论】:

    【解决方案2】:

    你可能会使用:

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

    每个 CSS 属性都有自己的对象模型。通常那些包含'-'的css属性是使用java模型编写的。

    例如:

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

    如果你想获取为一个对象定义的所有 css 属性,你必须将它们一一列出,因为即使你没有在样式表中设置属性,对象也会有它默认值。

    【讨论】:

    • “Java 模型”是什么意思?你是说camelCase?
    • 如果你仔细阅读这个问题,你会发现 OP 是 not 使用内联 CSS。
    【解决方案3】:

    Polyfill 使用 javascript 获取元素的当前 CSS 样式...访问link 了解更多信息

    /**
    * @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   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2012-06-01
      相关资源
      最近更新 更多