style 改变节点样式
写法:节点.style
- 访问属性
-
每个节点都有一个style属性,访问可以直接节点.style.color;如果是两个单词的:如font-size,节点.style.fontSize,去掉“-”(在css中使用“-”),使用驼峰命名法。
-
值是一个字符串。
changeBtn.onclick=function(){ d1.style.width='200px'; //必须加上引号 d1.style.height = "200px"; d1.style.backgroundColor='red'; }
-
通过节点.syle.css,访问的是内嵌的,设置的也是内嵌的.()直接用style访问属性,得到内嵌,访问的也是内嵌
-
使用 !important 优先级最高,在onclick内重新设置改变的内容也不能改变原来的样式。(不能用在JS)
获取、设置内部样式表方法
styleSheets
- styleSheets 得到样式表
- link 也是样式表,外部样式
-
通过:document.styleSheets 得到一个样式表,返回值是一个伪数组,但是外部样式表的cssRules为null;
console.log(document.styleSheets[0] ); // 返回: styleSheetList{0:CSSStyleSheet,length:1} 伪数组 console.log(document.styleSheets[1].cssRules[0]);// 外部样式表null console.log(document.styleSheets[1].cssRules[0].style.width); //style.width 得到内部样式 document.styleSheets[1].cssRules[0].style.width='200px'; //改变width内部样式
cssRules
- 得到样式规则
- 外部样式表的cssRules为null
最终样式
- 最终呈现在页面的样式
currentStyle
- 用在IE
getComputedStyle
-
window.getComputedStyle 可省略wimdow, 只能用在DOM浏览器,只读,不能改
-
得到一串伪数组。可以通过下标和属性名访问
console.log(window.getComputedStyle(d1).width); // 得到内嵌设置的 console.log(window.getComputedStyle(d1)); // 得到全局的样式,默认值