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

JS利用DOM获取或设置元素的样式

2017-09-16 20:10 495 查看
1.利用DOM操作行内样式表

              1)属性值的获取:元素节点.style.属性名,注意如果是类似于font-size这种属性,需要改为fontSize写法

              2)属性值的设置:元素节点.style.属性名 = “值”

       2.利用DOM操作内部样式表或外部样式表

              1)IE浏览器下:元素节点.currentStyle

              2)谷歌或火狐下:window.getComputedStyle(元素节点,null);

              3)兼容写法

                   格式1:var  sty  =  元素节点.currentStyle==undefined ? window.getComputedStyle(元素节点,null) : 元素节点.currentStyle

                     格式2:var  sty  = 元素节点.currentStyle|| window.getComputedStyle(元素节点,null);

              4)注意:外部样式或行内样式在JS下面是无法更改的,如果要更改,可以使用添加行内样式的形式更改,即元素节点.style.属性名 = 属性值;

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background: blue;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
var div = document.querySelector("div");
console.log(div.style.width); //什么也没有
var sty = div.currentStyle || window.getComputedStyle(div,null);
console.log(sty.width); //100px;
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: