JavaScript 中的样式与 CSS 操作
|
admin
2025年7月6日 14:14
本文热度 90
|
今天我就来跟大家聊聊 JavaScript 中操作样式的各种方法, 从最基础的 style 属性操作, 到现代 CSS-in-JS 方案,咱们一步步来.当我们想用 JavaScript 直接修改一个元素的样式时,最直接的方法就是操作它的 style
属性:const button = document.getElementById('myButton');
button.style.backgroundColor = 'blue';
button.style.color = 'white';
button.style.padding = '10px 20px';
这样操作后, 元素上就会添加内联样式, 优先级非常高 , 会覆盖外部 CSS 文件中的样式.* 属性名转换:CSS 属性中的连字符(如 background-color)
在 JavaScript中要改为驼峰命名(backgroundColor).
* 单位不能少:像 width
、height
、margin
这样的属性必须带上单位:
element.style.width = '100px';
element.style.width = 100;
* 批量设置: 可以用cssText
一次性设置多个样式:element.style.cssText = 'width: 100px; height: 200px; background: red;';
3)一个实际应用的场景,内联样式最适合用在需要动态计算的样式上,比如:
const progress = document.getElementById('progress');
progress.style.width = `${currentProgress}%`;
document.addEventListener('mousemove', (e) => {
const follower = document.getElementById('follower');
follower.style.left = `${e.clientX}px`;
follower.style.top = `${e.clientY}px`;
});
二、获取计算后的样式: getComputedStyle有时候我们需要获取元素最终渲染的样式(包括来自 CSS 文件的样式),这时候就需要 getComputedStyle
出场了.const element = document.getElementById('myElement');
const computedStyle = window.getComputedStyle(element);
console.log(computedStyle.width);
console.log(computedStyle.backgroundColor);
只读:getComputedStyle
返回的对象是只读的, 不能通过它修改样式.
获取所有属性:它会返回元素所有 CSS 属性的计算值, 即使你没设置过.
包含最终值:比如你设置了width: 50%,
它会返回计算后的像素值.
实际应用示例:
function isHidden(element) {
return window.getComputedStyle(element).display === 'none';
}
function getElementActualWidth(element) {
const style = window.getComputedStyle(element);
return (
parseFloat(style.width) +
parseFloat(style.paddingLeft) +
parseFloat(style.paddingRight) +
parseFloat(style.borderLeftWidth) +
parseFloat(style.borderRightWidth)
);
}
三、比起直接操作样式, 更推荐的做法是通过添加/移除 CSS 类来控制样式
1) 现代 JavaScript 提供了强大的classList
API:const box = document.getElementById('box');
box.classList.add('active', 'highlighted');
box.classList.remove('highlighted');
box.classList.toggle('active');
if (box.classList.contains('active')) {
console.log('元素有active类');
}
box.classList.replace('old-class', 'new-class');
const tabs = document.querySelectorAll('.tab');
const panels = document.querySelectorAll('.panel');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
panels.forEach(p => p.classList.remove('active'));
tab.classList.add('active');
const panelId = tab.getAttribute('data-panel');
document.getElementById(panelId).classList.add('active');
});
});
四、有时候我们需要更动态地控制样式, 比如添加或修改整个样式规则const style = document.createElement('style');
style.textContent = `
.highlight {
background-color: yellow;
border: 2px solid orange;
}
`;
document.head.appendChild(style);
const stylesheet = document.styleSheets[0];
stylesheet.insertRule('.error { color: red; }', stylesheet.cssRules.length);
stylesheet.deleteRule(0);
随着前端框架的流行,CSS-in-JS方案越来越受欢迎. 它们允许我们在JavaScript中编写 CSS, 并提供了许多强大功能.
CSS-in-JS是一种将CSS直接写在 JavaScript 文件中的技术,它通常有以下特点:
局部作用域样式(避免全局污染)
自动添加浏览器前缀
支持基于props的动态样式
自动处理关键CSS和代码分割
import styled from 'styled-components';
const Button = styled.button`
background: ${props => props.primary ? 'blue' : 'white'};
color: ${props => props.primary ? 'white' : 'blue'};
padding: 10px 20px;
border: 2px solid blue;
border-radius: 4px;
&:hover {
opacity: 0.8;
}
`;
<Button primary>主要按钮</Button>
<Button>次要按钮</Button>
import { css } from '@emotion/react';
const style = css`
background: blue;
color: white;
padding: 10px 20px;
&:hover {
opacity: 0.8;
}
`;
function MyComponent() {
return <button css={style}>点击我</button>;
}
阅读原文:原文链接
该文章在 2025/7/7 11:31:40 编辑过