样式操作
[ CSS 脚本化?!] 所谓样式操作,就是通过 JS 进行样式的获取和更新。
[1] HTMLElement.style 能够访问和修改元素的内联样式
- 访问元素的单个内联属性
const = document.getElementById('demo'); element.style.width; // '100px' element.style.background; // 'grey'
- 修改元素的单个内联属性
element.style.background = 'red';
[ cssText属性 ] style 还具有 cssText 的属性,它包含了一个元素所有的内联样式规则。
- 获取元素的所有内联属性
const element = document.getElementById('demo'); element.style.cssText; // "width:100px;height:100px;background:grey;"
- 批量修改元素的内联属性
element.style.cssText = 'width:100px;height:50px;background:red;'; 或 element.setAttribute('style','width:100px;height:50px;background:red;');通常来讲,访问元素属性只使用 style 是不够的,因为它只包含内联属性,而不包含样式表中的其他任何声明。
在实际场景中,比较适合操作特定元素的样式,如手机端网页中的搜索栏需要根据用户的不同手势动态显示或隐藏。
[2] window.getComputedStyle
该方法弥补了 style 属性只能获取内联样式的不足,它可以获取到最终应用在元素上的CSS属性对象(包括内联和样式表)。
const style = window.getComputedStyle(element[,pseudoElt]); // 第二个参数是可选的,用于描述伪类的字符串,所以它可以获取到元素伪类的样式
// 代码示例
<head>
<style>
.square{
width: 100px;
}
</style>
</head>
<body>
<div id="demo" class="square" style="height: 100px;"></div>
</body>
const element = document.getElementById('demo');
const style = window.getComputedStyle(element);
element.style.width; // ''
element.style.height; // '100px'
style.width; // '100px'
style.height; // '100px'
[3] HTMLElement.className 更新 className
对于在样式表使用 CSS 类选择器定义的 CSS 样式,可以修改元素的类名来操作 CSS 样式。
<head>
<style>
.square{width: 100px;height: 100px;background-color: darkred;}
.radius{border-radius: 50%;}
</style>
</head>
<body>
<div id="demo" class="square"></div>
<script>
var demo = document.getElementById('demo');
demo.className += ' radius'; // radius前面有一个空格
</script>
</body>
// 获取到的style是CSSStyleDelatation类的对象;IE9以下不支持,使用element.currentStyle。
[4] 操作样式表
- 动态加载 CSS 样式片段
function insertCSS(css){ const style = document.createElement('style'); style.type = 'text/css'; style.appendChild(document.createTextNode(css)); const head = document.getElementsByTagName('head')[0]; head.appendChild(style); } insertCSS('body{background:grey;}');
- 动态插入 CSS 外部样式表
function loadStyle(url){ const link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = url; const head = document.getElementsByTagName('head')[0]; head.appendChild(link); } loadStyle('/css/style.css');通过动态的替换样式表可以改变整个网站的外观,如网站的换肤功能。
[5] DOM CSSStyleSheet 接口

[ 样式表 ]通过 document.styleSheets 可以获取HTML中通过 link 元素和 style 元素包含的所有样式表;样式表是一个 CSSStyleSheet 对象,这个对象还可以通过 link 或 style 元素的 sheet 属性访问到。
它的 cssRules 属性包含了样式表中所有的 CSS 规则。
[ 样式规则 ]cssRules 中的每一项都是一个 CSSStyleRule 对象,表示 CSS 样式表中一个单独的规则集,可以通过这个对象操作样式表中的每一条规则。
CSSStyleRule 对象的 style 属性是一个 CSSStyleDeclaration 对象,表示一个 CSS 属性键值对的集合。除样式表中定义的 CSS 属性,元素的 style 属性获得的内联样式及通过 getComputedStyle 方法获取的样式属性,也是该对象。
通过样式表对象上提供的各种方法,我们可以查询和修改样式表中的规则,也可以达到操作样式的目的。