js获取css属性值的方法

js操作获取dom元素的样式属性值

obj.style: 它只能够获取通过style设置的元素CSS属性值:

  • html标签内通过style设置行内属性
  • 通过.dom.style.width="100px"这样类似设置。

无法获取定义在<style type="text/css">里面的属性,这时getComputedStyle()就可以发挥作用了 ,它可以获取到指定元素对应css属性的最终计算值。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style type=”text/css”>
	.ss{color:#cdcdcd;}
</style>
</head>
<body>
<div id='css88' class='ss' style='width:200px; height:200px; background:#333333'>JS获取CSS属性值</div>

<script type=”text/javascript”>
alert(document.getElementById(“css88″).style.width);//200px
alert(document.getElementById(“css88″).style.color);//null
</script>
</body>
</html>
  1. window.getComputedStyle(dom元素,【伪类】),不兼容IE浏览器(obj.currentStyle)。
window.getComputedStyle(el)等价于 document.defaultView.getComputedStyle(el)

“DOM2级样式”增强了document.defaultView,提供了getComputedStyle()方法。这个方法接受两个参数:要取得计算样式的DOM元素和一个伪元素字符串(例如“:after”)。如果不需要伪元素信息,第二个参数可以是null。getComputerStyle()方法返回一个实时的CSSStyleDeclaration对象,包含当前元素的所有计算的样式。当元素的样式更改时,它会自动更新本身。

<!DOCTYPE html>
<html lang="en">
<head>
<title>计算元素样式</title>
<style>
#myDiv {
    width:100px;
    height:200px;
}
</style>
<body>
<div id ="myDiv" style=" border:1px solid black"></div>
<script>
var myDiv = document.getElementById("myDiv");
var computedStyle = document.defaultView.getComputedStyle(myDiv, null);

alert(computedStyle.backgroundColor); //"red"
alert(computedStyle.width); //"100px"
alert(computedStyle.height); //"200px"
alert(computedStyle.border); //在某些浏览器中是“1px solid black”
</script>
</body>
</head>
</html></span>

下面这个函数,能够获取一个元素的任意 CSS 属性值。

    function  getStyle(element,attr){
            if(element.currentStyle){
                return element.currentStyle[attr]
            }else{
                return getComputedStyle(element).attr
           } 
      }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哆啦咪唏

看到这里了,不留下点什么吗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值