使用JS动态操作css的集中方法
在咱们深入一些复杂的知识之前,先回来顾一下一些基础知识。例如,咱们可以通过修改它的.style属性来编辑给定的HTMLElement的内联样式。
const el = document.createElement(‘div‘) el.style.backgroundColor = ‘red‘ // 或者 el.style.cssText = ‘background-color: red‘ // 或者 el.setAttribute(‘style‘, ‘background-color: red‘)
直接在.style对象上设置样式属性将需要使用驼峰式命名作为属性键,而不是使用短横线命名。 如果咱们需要设置更多的内联样式属性,则可以通过设置.style.cssText属性,以更加高效的方式进行设置 。
请记住,给cssText设置后原先的css样式被清掉了,因此,要求咱们一次死一堆样式 。
如果这种设置内联样式过于繁琐,咱们还可以考虑将.style与Object.assign()一起使用,以一次设置多个样式属性。
// ... Object.assign(el.style, { backgroundColor: "red", margin: "25px" })
这些“基本知识”比咱们想象的要多得多。.style对象实现CSSStyleDeclaration接口。
这说明它带还有一些有趣的属性和方法,这包括刚刚使用的.cssText,还包括.length(设置属性的数量),以及.item()、.getPropertyValue()和.setPropertyValue()之类的方法:
// ... const propertiesCount = el.style.length for(let i = 0; i < propertiesCount; i++) { const name = el.style.item(i) // ‘background-color‘ const value = el.style.getPropertyValue(name) // ‘re‘ const priority = el.style.getPropertyPriority(name) // ‘important‘ if(priority === ‘important‘) { el.style.removeProperty() } }
这里有个小窍门-在遍历过程中.item()方法具有按索引访问形式的备用语法。
// ... el.style.item(0) === el.style[0]; // true
CSS 类接着,来看看更高级的结构——CSS类,它在检索和设置时具有字符串形式是.classname。
// ... el.className = "class-one class-two"; el.setAttribute("class", "class-one class-two");
设置类字符串的另一种方法是设置class属性(与检索相同)。 但是,就像使用.style.cssText属性一样,设置.className将要求咱们在字符串中包括给定元素的所有类,包括已更改和未更改的类。
当然,可以使用一些简单的字符串操作来完成这项工作,还有一种就是使用较新的.classList属性,这个属性,IE9 不支持它,而 IE10 和 IE11 仅部分支持它。
classlist属性实现了DOMTokenList,有一大堆有用的方法。例如.add()、.remove()、.toggle()和.replace()允许咱们更改当前的 CSS 类集合,,而其他的,例如.item()、.entries()或.foreach()则可以简化这个索引集合的遍历过程。
// ... const classNames = ["class-one", "class-two", "class-three"]; classNames.forEach(className => { if(!el.classList.contains(className)) { el.classList.add(className); } });
Stylesheets一直以来,Web Api 还有一个StyleSheetList接口,该接口由document.styleSheets属性实现。 document.styleSheets 只读属性,返回一个由 StyleSheet 对象组成的 StyleSheetList,每个 StyleSheet 对象都是一个文档中链接或嵌入的样式表。
for(styleSheet of document.styleSheets){ console.log(styleSheet); }
通过打印结果咱们可以知道,每次循环打印的是 CSSStyleSheet 对象,每个 CSSStyleSheet 对象由下列属性组成:
CSS Style Sheet对象方法:
有了StyleSheetList的全部内容,咱们来CSS StyleSheet本身。 在这里就有点意思了, CSS StyleSheet扩展了StyleSheet接口,并且只有这种只读属性,如.ownerNode,.href,.title或.type,它们大多直接从声明给定样式表的地方获取。回想一下加载外部CSS文件的标准HTML代码,咱们就会明白这句话是啥意思:
<head> <link type="text/css" href="http://www.mamicode.com/style.css" title="Styles"> </head>
现在,咱们知道HTML文档可以包含多个样式表,所有这些样式表都可以包含不同的规则,甚至可以包含更多的样式表(当使用@import时)。CSSStyleSheet有两个方法:、.insertrule()和.deleterule() 来增加和删除 Css 规则。
// ... const ruleIndex = styleSheet.insertRule("div {background-color: red}"); styleSheet.deleteRule(ruleIndex);
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/39977.html