javascript 获取元素的真实,最终的css样式

elem.style.xxx 只能获取内联的css属性,对<head>内的或link 外部样式的无能为力。

<style>
h1{
font-size:1.6em;
color:red;
}
</style>


</head>

<body>
<h1 id="title">hello world</h1>
<p>this is a test txt</p>

<script>
var x=document.getElementById("title");
document.write(x.style.color);
</script>

其实

x.style.color="";
所以看不到样式信息.
A function for finding the computed style value of an element is shown in Listing 7-1

// Get a style property (name) of a specific element (elem)
function getStyle( elem, name ) {
// If the property exists in style[], then it's been set
// recently (and is current)
if (elem.style[name])
    return elem.style[name];
// Otherwise, try to use IE's method

else if (elem.currentStyle) return elem.currentStyle[name]; // Or the W3C's method, if it exists

else if (document.defaultView && document.defaultView.getComputedStyle) { // It uses the traditional 'text-align' style of rule writing, // instead of textAlign name = name.replace(/([A-Z])/g,"-$1"); name = name.toLowerCase(); // Get the style object and get the value of the property (if it exists) var s = document.defaultView.getComputedStyle(elem,""); return s && s.getPropertyValue(name); // Otherwise, we're using some other browser } else return null; }

w3c办法,它使用的是通用的text-align而非textAlign;所以先要把属性名替换。

注意;几乎任何属性都会返回表示元素样式的字符串而非数值(比如是100px而非100);

<html>
<head>
    <style>p { height: 100px; }</style>
    <script>
    window.onload = function(){
        // Locate the paragraph to check the height of
        var p = document.getElementsByTagName(“p”)[0];

        // Check the height the traditional way
        alert( p.style.height + “ should be null” );

        // Check the computed value of the height
        alert( getStyle( p, “height” ) + “ should be 100px” );
    };
    </script>
</head>
<body>
    <p>I should be 100 pixels tall.</p>
</body>
</html>

上面展示了如何获取一个dom元素的css属性的最终 真实值。 需要注意的是:这个函数忽略的其他的计量单位(如百分比)。所以这个方法并不完美,但已经是一个很好的开端。

chrome 下 height:x %;

不过是x是什么,都是18。

Ie的currentStyle 对象 代表了在全局样式表、内嵌样式和 HTML 标签属性中指定的对象格式和样式。http://msdn.microsoft.com/en-us/library/ie/ms535231(v=vs.85).aspx

 

W3c :
document.defaultView
browsers returns the window object associated with the document or null if none available
var win = document.defaultView;

getComputedStyle() gives the final used values of all the CSS properties of an element.
var style = window.getComputedStyle(element[, pseudoElt]);
The returned style is a CSSStyleDeclaration object.
pseudoElt Optional
A string specifying the pseudo-element to match. Must be null (or not specified) for regular elements.
通常的元素必须为null。

 CSSStyleDeclaration  方法
getPropertyValue(propertyName)
removeProperty(propertyName)

参考:https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

 
原文地址:https://www.cnblogs.com/youxin/p/2695476.html