2012-03-16 278 views
21

如何获取元素CSS属性(例如width/height),因为它是用CSS规则设置的,无论它是以什么单位设置的(例如百分比/ em/px)? (在Google Chrome中,最好是无框架的)。获取元素的CSS属性(宽度/高度)值(如百分比/ em/px/etc)

使用getComputedStyle以像素为单位返回当前值,jQuery中的css()也是如此。

例如:

<div class="b">first</div> 
<div id="a" class="a">second</div> 

<style> 
    div  { width: 100px; } 
    x, div#a { width: 50%; } 
    .a  { width: 75%; } 
</style> 

尽管迭代在这个例子中所有div元件,我想能够得到第二div小号宽度50%(和第一作为100px)。


Chrome元素检查器可以显示CSS属性值,因此它应该可以在Chrome中使用。

Chrome element inspector showing property value as they were set


不是一个确切复制链接的问题,因为没有公认的答案有一个简单的黑客工具,产生一个百分比宽度不管设置什么样的宽度。其余的你必须知道选择器用于制定活动规则?如何知道?

+1

这回答可能是你在找什么:http://stackoverflow.com/a/744450/684934 – bdares 2012-03-16 01:29:22

+0

那些答案根本不适合,因为我需要通过元素而不是某些特定的选择器来获取值。 **不完全重复!** – Qtax 2012-03-16 01:37:10

+0

%仅在其父元素的上下文中相关,因此您需要根据当前元素和父元素的比较宽度进行处理 – Dan 2012-03-16 02:30:30

回答

1

大家好消息!在w3的草稿中,似乎有一个CSS Typed OM

快速阅读这个文档,看来这个的目标可能是规范,就是为了缓解从CSS中获取CSSOM值。

我们这里这样做的真正重要的是,我们将有一个CSSUnitValue API,这将能够解析CSS值的形式

{ 
    value: 100, 
    unit: "percent", // | "px" | "em" ... 
    type: "percent" // | "length" 
} 

的对象和Window.getComputedStyleMap()方法,从我们将能够获得实际应用于我们元素的价值。

截至今天,似乎只有Chrome未开始虽然实现它,你需要将实验网络平台上切换功能标志about:flags ...

(() => { 
 
    if (!window.getComputedStyleMap && !Element.prototype.computedStyleMap) { 
 
    console.error("Your browser doesn't support CSS Typed OM"); 
 
    return; 
 
    } 
 
    document.querySelectorAll('.test') 
 
    .forEach((elem) => { 
 
     let styleMap; 
 
     // As defined in specs' drafts 
 
     if (window.getComputedStyleMap) { 
 
     styleMap = window.getComputedStyleMap(elem); 
 
     } 
 
     // Currently Chrome attaches it to the Element proto 
 
     else styleMap = elem.computedStyleMap(); 
 

 
     const widthValue = styleMap.get('width'); 
 
     console.log(elem, widthValue); 
 
    }); 
 

 
/* outputs 
 

 
    <div class="b test">first</div> 
 
    CSSUnitValue { 
 
    "type": "length", 
 
    "unit": "px", 
 
    "value": 100, 
 
    [__proto__] 
 
    } 
 
    
 
    <div id="a" class="a test">second</div> 
 
    CSSUnitValue { 
 
    "type": "percent", 
 
    "unit": "percent", 
 
    "value": 50, 
 
    [__proto__] 
 
    } 
 

 
*/ 
 

 
})();
div.test { width: 100px; } 
 
x,div#a { width: 50%; } 
 
.a { width: 75%; }
<div class="b test">first</div> 
 
<div id="a" class="a test">second</div>

+0

看起来不错。你的代码示例返回的宽度是什么结果?你能否将其添加到答案中,以便更容易地看到它的作用。 – Qtax 2018-03-07 15:12:32

+0

@Qtax好点,我在代码的片段中添加了输出作为评论 – Kaiido 2018-03-08 01:31:38

21

它并不像很简单,就像调用WebKits getMatchedCSSRules()一样,它确实按照优先级顺序返回匹配的规则(虽然我没有看到文档中提到这个顺序),但是顺序不考虑属性impor优先级,不包括元素样式。所以我结束了此功能:

getMatchedStyle

function getMatchedStyle(elem, property){ 
    // element property has highest priority 
    var val = elem.style.getPropertyValue(property); 

    // if it's important, we are done 
    if(elem.style.getPropertyPriority(property)) 
     return val; 

    // get matched rules 
    var rules = getMatchedCSSRules(elem); 

    // iterate the rules backwards 
    // rules are ordered by priority, highest last 
    for(var i = rules.length; i --> 0;){ 
     var r = rules[i]; 

     var important = r.style.getPropertyPriority(property); 

     // if set, only reset if important 
     if(val == null || important){ 
      val = r.style.getPropertyValue(property); 

      // done if important 
      if(important) 
       break; 
     } 
    } 

    return val; 
} 

考虑下面的代码和样式规则:

<div class="b">div 1</div> 
<div id="a" class="a d2">div 2</div> 
<div id="b" class="b d3" style="width: 333px;">div 3</div> 
<div id="c" class="c d4" style="width: 44em;">div 4</div> 

<style> 
div  { width: 100px; } 
.d3  { width: auto !important; } 
div#b { width: 80%; } 
div#c.c { width: 444px; } 
x, div.a { width: 50%; } 
.a  { width: 75%; } 
</style> 

这个JS代码

var d = document.querySelectorAll('div'); 

for(var i = 0; i < d.length; ++i){ 
    console.log("div " + (i+1) + ": " + getMatchedStyle(d[i], 'width')); 
} 

提供了以下宽度为div S:

div 1: 100px 
div 2: 50% 
div 3: auto 
div 4: 44em 

At jsFiddle

+0

它是你写的一个很棒的函数,但它只返回内联样式规则,而不是在css中定义的规则。如何获得这些?尽管它是一个非常有用的功能。 – Pramod 2014-09-29 05:50:08

+1

@Pramod,该函数确实会返回用CSS规则编写的CSS值(这就是它的全部要点),正如您可以看到的,仔细观察该示例。但它仅适用于支持'getMatchedCSSRules()'的浏览器,即Chrome和其他基于WebKit/Blink的浏览器(如问题中所要求的那样)。太糟糕了,更多的浏览器不支持。 Altho Mozilla有一个实现它的功能请求:https://bugzilla.mozilla.org/show_bug.cgi?id=438278 – Qtax 2014-09-29 07:03:02

+0

在safari和chrome中工作...不在FF中...病态仍然,谢谢! – 2015-11-10 23:27:51

2

有一个较新的副本后与一个伟大的答案here。该答案适用于jQuery,但易于实现in pure js

function getDefaultStyle(element, prop) { 
    var parent = element.parentNode, 
     computedStyle = getComputedStyle(element), 
     value; 
    parent.style.display = 'none'; 
    value = computedStyle.getPropertyValue(prop); 
    parent.style.removeProperty('display'); 
    return value; 
} 
+2

这不会获得与创作的单位相同的单位值,但它确实为您提供了' px','%'或'auto',这对某些应用程序来说可能已经足够了。所以诀窍是设置父级显示无,并获得计算风格。有趣。 +1 – Qtax 2015-07-01 17:20:38

+0

这太好了......我很惊讶它可以工作,但它似乎不适用于视口单元(vh,vw等)。 – Andrew 2017-04-20 03:54:39