一、查询CSS样式
1.查询style属性样式
- element.style.cssAttrName
- 要查询的样式必须写在style 属性里
2.查询计算出的样式
-
window.getComputedStyle
- IE9+ 标准浏览器
- getComputedStyle 第二个参数可以指定after或before
-
element.currentStyle
-
IE浏览器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>查询元素的计算样式</title> </head> <body> <script> console.log(document.body.style.margin); try { /*IE8-不支持*/ var styleObj = window.getComputedStyle(document.body); /*所有的默认样式*/ console.log(styleObj); console.log(styleObj.margin); console.log(styleObj.marginLeft); } catch (e) { /*兼容IE*/ console.log(document.body.currentStyle) console.log(document.body.currentStyle.marginLeft) } </script> </body>
-
二、脚本化CSS类
1.classList对象(IE10+)
- add() 添加
- remove() 移除
- toggle() 有就不添加,没有就添加
三、脚本化样式表
1. CSSStyleSheet对象
- document.styleSheets 获取 link和style 组成的集合
- styleSheet styleSheet的每一成员 表示一个link 或一个 style
- cssRules styleSheet的属性 表示每一条记录
- 开启或关闭 css样式 styleSheet.disabled 属性
- 添加查询与删除规则
-
添加
- styleSheet.insertRule(string, index)
- styleSheet.addRule(selecter, string, index) IE
-
删除
-
styleSheet.deleteRule(index)
-
styleSheet.removeRule() IE
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>函数 -- 获取元素的计算样式</title> <link rel="stylesheet" href="style.css"> <style> body{ margin:0; } </style> <style> .box{ 400px; height:300px; border:1px solid #ccc; background-color:#f5f5f5; } </style> </head> <body> <div class="box"></div> <script> function getStyle(element, attrName) { try { return window.getComputedStyle(element)[attrName]; } catch (e) { return element.currentStyle[attrName]; } } console.log(document.styleSheets); var boxEle = document.querySelector(".box"); console.log(getStyle(boxEle, "width")); //禁用CSS样式 document.styleSheets[2].disabled = true; </script> </body> </html>
-
-