JS中style、currentStyle、getComputedStyle的区别

在说到它们之间的区别时,我们首先说说层叠样式表的是三种形式:

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。


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

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

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

实例:

<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="显示" οnclick="test()" />
      </form>






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值