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>