🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## getAttribute 操作 css ``` div.setAttribute( 'style', 'background-color:red;' + 'border:1px solid black;' ); //or e.style.fontSize = '18px'; e.style.color = 'black'; ``` ## CSSStyleDeclaration 接口 ### 实例属性 获取实例 `var divStyle = document.querySelector('div').style` #### cssText ``` var divStyle = document.querySelector('div').style; divStyle.cssText = 'background-color: red;' + 'border: 1px solid black;' + 'height: 100px;' + 'width: 100px;'; ``` //删除行内样式 `divStyle.cssText = ''; ` #### length ``` // <div id="myDiv" // style="height: 1px;width: 100%;background-color: #CA1;" // ></div> var myDiv = document.getElementById('myDiv'); var divStyle = myDiv.style; divStyle.length // 3 ``` ### 实例方法 #### getPropertyValue() 参数属性名,返回属性值 ``` // <div id="myDiv" style="margin: 10px!important; color: red;"/> var style = document.getElementById('myDiv').style; style.margin // "10px" style.getPropertyValue("margin") // "10px" ``` #### removeProperty() 移除属性 ``` style.removeProperty('color') // 'red' ``` #### item() 整数参数,返回属性名 ``` style.item(0) //等效 style[0] ``` #### setProperty() 参数,样式名,样式值 ``` style.setProperty('border', '1px solid blue'); ``` ## CSS 模块的侦测-判断浏览器是否支持某个属性 存在返回字符串,没有设置返回空字符串,不支持返回 `undefined` 需要考虑不同浏览器的前缀 ``` typeof element.style.animationName === 'string'; typeof element.style.transform === 'string'; ``` ## CSS 对象 ### CSS.escape() 转义css 选择选择器中的特殊字符 ``` <div id="foo#bar"> document.querySelector('#' + CSS.escape('foo#bar')) //#foo\#bar ``` ### CSS.supports() 判断当前是否支持css规则 ``` // 第一种写法 CSS.supports('transform-origin', '5px') // true // 第二种写法 CSS.supports('display: table-cell') // true 结尾不可带分号 ``` ### window.getComputedStyle() 最终样式 ``` var div = document.querySelector('div'); var styleObj = window.getComputedStyle(div); styleObj.backgroundColor ``` 第二元素设置伪元素 `var result = window.getComputedStyle(div, ':before'); ` 注意: * CSSStyleDeclaration 实例返回的 CSS 值都是绝对单位。比如,长度都是像素单位(返回值包括`px`后缀),颜色是`rgb(#, #, #)`或`rgba(#, #, #, #)`格式。 * CSS 规则的简写形式无效。比如,想读取`margin`属性的值,不能直接读,只能读`marginLeft`、`marginTop`等属性;再比如,`font`属性也是不能直接读的,只能读`font-size`等单个属性。 * 如果读取 CSS 原始的属性名,要用方括号运算符,比如`styleObj['z-index']`;如果读取骆驼拼写法的 CSS 属性名,可以直接读取`styleObj.zIndex`。 * 该方法返回的 CSSStyleDeclaration 实例的`cssText`属性无效,返回`undefined`。 ### StyleSheet 接口 ``` var sheets = document.styleSheets; var sheet = document.styleSheets[0]; sheet instanceof StyleSheet // true ```