js实现css
JavaScript 实现 CSS 的方法
在 JavaScript 中操作 CSS 有多种方式,包括直接修改样式、操作类名、使用 CSSOM 等。以下是几种常见方法:
修改元素的 style 属性
通过元素的 style 属性可以直接修改内联样式:
const element = document.getElementById('myElement');
element.style.color = 'red';
element.style.backgroundColor = '#f0f0f0';
操作 classList 属性
通过 classList 可以添加、移除或切换 CSS 类:
element.classList.add('active');
element.classList.remove('inactive');
element.classList.toggle('highlight');
动态创建样式表
可以通过 document.createElement 创建 <style> 元素并插入到文档中:
const style = document.createElement('style');
style.textContent = `
.myClass {
color: blue;
font-size: 16px;
}
`;
document.head.appendChild(style);
使用 CSSOM
通过 CSSStyleSheet 接口可以操作现有的样式表:
const sheet = document.styleSheets[0];
sheet.insertRule('body { background-color: yellow; }', sheet.cssRules.length);
设置 CSS 变量
可以通过 JavaScript 动态修改 CSS 变量:
document.documentElement.style.setProperty('--main-color', '#ff0000');
使用 window.getComputedStyle
获取元素最终计算的样式值:
const styles = window.getComputedStyle(element);
console.log(styles.getPropertyValue('color'));
注意事项
- 直接修改
style属性会覆盖内联样式,优先级较高 - 修改类名更适合批量样式变更
- CSSOM 操作适合需要精细控制样式表的情况
- CSS 变量提供了一种灵活的主题切换方式







