如何在javascript中获取HTML元素的样式值?

sta*_*tan 60 html javascript css stylesheet

我正在寻找一种方法来从样式标签上设置样式的元素中检索样式.

<style> 
#box {width: 100px;}
</style>
Run Code Online (Sandbox Code Playgroud)

在身体里

<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)

我正在寻找没有使用库的直接javascript.

我尝试了以下方法,但继续收到空白:

alert (document.getElementById("box").style.width);  
alert (document.getElementById("box").style.getPropertyValue("width"));
Run Code Online (Sandbox Code Playgroud)

我注意到,如果我使用javascript设置样式,但我无法使用上述样式,但无法使用样式标记.

CMS*_*CMS 78

element.style属性仅让您知道在该元素中定义为内联的CSS属性(以编程方式或在元素的style属性中定义),您应该获得计算出的样式.

以跨浏览器的方式做起来并不是那么容易,IE有自己的方式,通过element.currentStyle属性,以及DOM Level 2 标准方式,由其他浏览器实现的是通过该document.defaultView.getComputedStyle方法.

这两种方法有差异,例如,在IE element.currentStyle属性期待您访问的两个或多个单词组成的CCS属性名驼峰(例如maxHeight,fontSize,backgroundColor等),标准的方式希望用破折号分隔的字词的属性(如max-height,font-size,background-color,等等).

此外,IE element.currentStyle将返回指定单位中的所有大小(例如12pt,50%,5em),标准方式将始终以像素为单位计算实际大小.

我前段时间做了一个跨浏览器的功能,它允许你以跨浏览器的方式获取计算出的样式:

function getStyle(el, styleProp) {
  var value, defaultView = (el.ownerDocument || document).defaultView;
  // W3C standard way:
  if (defaultView && defaultView.getComputedStyle) {
    // sanitize property name to css notation
    // (hypen separated words eg. font-Size)
    styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
    return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  } else if (el.currentStyle) { // IE
    // sanitize property name to camelCase
    styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
      return letter.toUpperCase();
    });
    value = el.currentStyle[styleProp];
    // convert other units to pixels on IE
    if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
      return (function(value) {
        var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
        el.runtimeStyle.left = el.currentStyle.left;
        el.style.left = value || 0;
        value = el.style.pixelLeft + "px";
        el.style.left = oldLeft;
        el.runtimeStyle.left = oldRsLeft;
        return value;
      })(value);
    }
    return value;
  }
}
Run Code Online (Sandbox Code Playgroud)

对于某些情况,上述函数并不完美,例如对于颜色,标准方法将以rgb(...)表示法返回颜色,在IE上,它们将在定义时返回它们.

我目前正在撰写该主题的一篇文章,您可以在此处跟踪我对此功能所做的更改.

  • [似曾相识](http://stackoverflow.com/questions/2531737/javascript-incapable-of-getting-elements-max-height-via-element-style-maxheight) (2认同)
  • @BalusC:我认为这个问题更通用*,也许主持人可以合并它们?... (2认同)
  • `document.defaultView`是`window`.因此,您可以直接使用`getComputedStyle`代替`document.defaultView.getComputedStyle`. (2认同)
  • 您的开头段落解释了为什么将内联 CSS 移动到单独的文件后,我的 Javascript 无法正常工作。我在网上找到的唯一指出这一点的地方,谢谢! (2认同)

jus*_*_de 19

我相信你现在能够使用Window.getComputedStyle()

文档MDN

var style = window.getComputedStyle(element[, pseudoElt]);
Run Code Online (Sandbox Code Playgroud)

获取元素宽度的示例:

window.getComputedStyle(document.querySelector('#mainbar')).width
Run Code Online (Sandbox Code Playgroud)


Jar*_*yth 10

jQuery中,你可以做到alert($("#theid").css("width")).

- 如果你还没看过jQuery,我强烈推荐它; 它使许多简单的javascript任务毫不费力.

更新

为了记录,这篇文章是5岁.网络已经开发,移动等等.有一些方法可以使用Plain Old Javascript来做到这一点,这是更好的方法.

  • 他在问题中特别指出他不想使用库(jQuery是一个库......) (5认同)