操作元素节点上的 style 属性
el.style.backgroundColor = "red";
el.stvle.fontSize = "1Opx";
el.style.cssText ="background-color: green; font-size: 40px;
classList
- 可预先定义好 class 类名的样式,后面只需添加 class 即可达到切换样式的需求
el.classList.toggle("className", true)
el.classList.add("aa", "bb")
el.classList.remove("aa" , "bb")
操作 style 节点内容
<body>
<style id="sty">
.box {
color: green;
}
</style>
<button id="btn">变色</button>
<di class="box">内容</di>
<script>
btn.addEventListener("click", () => {
sty.textContent = sty.textContent.replace("color: green;", "color: pink;");
});
</script>
</body>
操作已有 style 节点
- CSSOM:CSS Object Model 是一组允许用 JavaScript 操纵 CSS 的 APl
<body>
<style id="sty">
.box {
color: green;
}
</style>
<button id="btn">变色</button>
<di class="box">内容</di>
<script>
btn.addEventListener("click", () => {
const styleSheets = Array.from(document.styleSheets);
const sty = styleSheets.find(item => item.ownerNode.id === "sty");
const rule = Array.from(sty.rules).find(rule => rule.selectorText === ".box");
const styleMap = rule.styleMap;
styleMap.set("background-color", "pink");
});
</script>
</body>
操作外部样式
<body>
<link rel="stylesheet" href="./index.css">
<button id="btn">变色</button>
<di class="box">内容</di>
<script>
btn.addEventListener("click", () => {
const styleSheets = Array.from(document.styleSheets);
const sty = styleSheets.find(s => s.href.endsWith("index.css"))
const rule = Array.from(sty.rules).find(rule => rule.selectorText === ".box")
const styleMap = rule.styleMap;
styleMap.set("background-color", "orange");
});
</script>
</body>
动态创建 link 节点引入样式
function importCssByUrl(url) {
const link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.head.appendChild(link);
}
window.getComputeStyle
- 返回一个对象,包含元素计算之后的 css 属性值
- 语法:
window.getComputedStyle(element, [pseudoElt]) pseudoElt 参数可以让它查询伪元素
- 注意此方式获取的是最终计算之后的样式值,而且会引起重排
<body>
<div class="box">云牧</div>
<style>
.box:before {
content: "你好";
font-size: 1.6rem;
}
</style>
<script>
const styleDeclaration = window.getComputedStyle(document.querySelector(".box"), "before");
console.log(styleDeclaration.content, styleDeclaration.fontSize);
</script>
</body>
重绘和重排
- 重排:元素的尺寸、结构、或某些属性发生改变时,浏览器重新渲染部分或全部文档的过程称为重排
- 重绘:元素样式的改变并不影响它在文档流中的位置或者尺寸的时候,例如:color, backgound-color, outline-color 等,浏览器会重新绘制元素,这个过程称为重绘
<body>
<style>
.ani {
position: absolute;
left: 0;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: orange;
transition: 3s;
}
</style>
<button id="btnAdd">动态创建节点并动画</button>
<div id="container"></div>
<script>
btnAdd.addEventListener("click", () => {
const div = document.createElement("div");
div.className = "ani";
container.appendChild(div);
div.style.left = "200px";
});
</script>
</body>