1.scrollIntoView()方法
该方法是将调用的元素滚动到浏览器窗口的可见区域。
它接受的参数类型可以为布尔值。
布尔值:true(默认值)和false。为true的话,代表调用的元素顶部与可滚动祖先的可见区域的顶部对齐。为false的话,代表调用的元素与可滚动的祖先元素的可见区域的底部对齐。
const divEle = document.querySelector("div"); // 元素与可滚动祖先元素的可见区域的顶部对齐 div.scrollIntoView(); // 元素与可滚动祖先元素的可见区域的底部对齐 div.scrollIntoView(false);
2.getComputedStyle()
在DOM2级样式中增强了document.defaultView,提供了getComputedStyle()方法,该方法会获取到style样式表中的属性的值。之前也用过这种方法,就是只是单一的为了计算style样式表中的属性值。
该方法会包含两个参数,参数一是要计算的样式的元素,参数二是伪元素的字符串(":after,:before"),如果没有可以是写null。
下面👇举个简单的例子和要注意的点。
/* <style> div { width: 100px; height: 200px; } </style> */ /* html元素div <div style={width: 100px; height: 100px;}>test div</div> */ const divEle = document.querySelector("div"); // 获取div元素的计算后的样式的属性值 const divEleGetComputed = document.defaultView.getComputedStyle(divEle, null); console.log(divEleGetComputed.width); // "100px" console.log(divEleGetComputed.height); // "100px",这里是因为样式表中的width和height的值被 行内样式给覆盖了,所以是100px
注意:该方法的参数二不能省略,并且计算的样式都是都读的,不能修改计算后的样式对象中的css属性。由于IE浏览器中对该方法不支持,所以可以使用currentStyle进行获取即可,用法和上面的一样。(divEle.currentStyle.weight/divEle.currentStyle.height)
3.操作样式表中的规则
操作样式表中的规则,可以使用styleSheet属性,它可以获取link引用外文件的样式表和style样式表。然后通过cssRules属性可以获取到一个样式表中的数组列表,使用[]或者item()方法都可以获取指定的样式规则,进行操作。我们之前在操作这些样式规则时,大多还是使用style去动态操作样式规则。这里有两个操作样式表中的方法,insertRule和deleteRule()(在IE中对应的是addRule和removeRule)。
这里当做一个回顾,这两个方法接收到额参数不一样,insertRule接受两个参数,参数一是选择符和样式文本字符串,参数二是插入的索引位置。(addRule接受三个参数,参数一是选择符的文本字符串,参数二是样式规则文本字符串,参数三是插入的索引位置)。deleteRule和removeRule方法一样都是只接受一个字符串,就是删除规则的索引位置。
/* // 通用的样式表 <style> div { width: 100px; height: 100px; background-color: blue; } p { border: 1px solid red; } </style> */
const sheet = document.styleSheets[0]; // 在非IE浏览器和IE浏览器上做一下兼容 const rules = sheet.cssRules || sheet.rules; // 获取样式规则的列表 for (let i = 0, i = rules.length; i < len; i++) { const rule = rules[i]; // 获取规则选择符文本为div的雅士规则 if (rule.selectorText === "div") { console.log(rule.style.cssText); // " width: 100px;height: 100px;color: red;" console.log(rule.style.width); // "100px" console.log(rule.style.backgroundColor); // "blue" break; } }
此外可以通过style属性进行动态修改样式规则的属性值。
const sheet = document.styleSheets[0]; const rule = sheet.cssRules[0] || sheet.rules[0]; rule.style.backgroundColor = "green"; // 修改背景颜色为绿色
往样式表中插入、删除一条规则。
const sheet = document.styleSheets[0]; // 对IE和非IE浏览器创建通用方法 function insertRuleFun (sheet, selector, cssText, index) { // 插入一条body的样式规则 if (sheet.insertRule) { // 非IE浏览器 sheet.insertRule(`${selector}{${cssText}}`, index); } else if (sheet.addRule) { // IE浏览器 sheet.addRule(selector, cssText, index); } } // 调用函数 const sheet = document.styleSheets[0]; insertRuleFun(sheet, "body", "background-color: silver", 0); // 移除一条规则 function deleteRuleFun (sheet, index) ( // 删除div样式规则 if (sheet.deleteRuleFun) { // IE浏览器 sheet.deleteRule(index); } else if (sheet.removeRule) { sheet.removeRule(index); } ) deleteRuleFun(sheet, 1);
网友评论