您的位置:首页 > Web前端 > JavaScript

JS中style、currentStyle、getComputedStyle的区别

2016-11-27 22:16 447 查看
在说到它们之间的区别时,我们首先说说层叠样式表的是三种形式:

1,内联样式:在HTML标签用style属性设置

    例如:<p style = "color : #456">内联样式</p>

2.嵌入样式 :通过<head>标签内通过<style>标签设置

<style type="text/css">

p {color:#456}

</style>

3. 外部样式:通过<link>标签设置

<link rel="stylesheet" href="path/style.css" type="text/css">

p{{color:#456};

区别:

使用style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。

currentStyle是兼容IE浏览器的。

getComputedStyle与currentStyle作用相同,但是适用于opera、firefox,safari、chrome。

getComputedStyle与style的区别
只读与可写:

        getComputedStyle方法是只读的,只能获取样式,不能设置;而element.style能读能写
获取的对象范围:

      getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(即使没有CSS代码,也会把默认的都显示出来);而element.style只能获取元素style属性中的CSS样式。因此对于一个光秃秃的元素<p>,getComputedStyle方法返回对象中length属性值(如果有),而element.style就是0。

注意:getComputerStyle()方法的第一个参数为元素,第二个参数为伪类,返回一个CSSStyleDeclaration对象。

实例:

[html] view
plain copy

 print?





<script type="text/javascript">  

            function test(){  

                var p = document.getElementById("p1");  

                var cla = window.getComputedStyle(p1,null);  

                      

                alert(cla["backgroundColor"]);  

            }  

        </script>  

<p id="p1" style="background-color: blueviolet;">你好啊,地球人</p>  

      <form>  

        <input type="button" value="显示" onclick="test()" />  

      </form>  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: