今天我就來跟大家聊聊 JavaScript 中操作樣式的各種方法, 從最基礎(chǔ)的 style 屬性操作, 到現(xiàn)代 CSS-in-JS 方案,咱們一步步來.當(dāng)我們想用 JavaScript 直接修改一個(gè)元素的樣式時(shí),最直接的方法就是操作它的 style
屬性:const button = document.getElementById('myButton');
button.style.backgroundColor = 'blue';
button.style.color = 'white';
button.style.padding = '10px 20px';
這樣操作后, 元素上就會(huì)添加內(nèi)聯(lián)樣式, 優(yōu)先級(jí)非常高 , 會(huì)覆蓋外部 CSS 文件中的樣式.* 屬性名轉(zhuǎn)換:CSS 屬性中的連字符(如 background-color)
在 JavaScript中要改為駝峰命名(backgroundColor).
* 單位不能少:像 width
、height
、margin
這樣的屬性必須帶上單位:
element.style.width = '100px';
element.style.width = 100;
* 批量設(shè)置: 可以用cssText
一次性設(shè)置多個(gè)樣式:element.style.cssText = 'width: 100px; height: 200px; background: red;';
3)一個(gè)實(shí)際應(yīng)用的場(chǎng)景,內(nèi)聯(lián)樣式最適合用在需要?jiǎng)討B(tài)計(jì)算的樣式上,比如:
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`;
});
二、獲取計(jì)算后的樣式: getComputedStyle有時(shí)候我們需要獲取元素最終渲染的樣式(包括來自 CSS 文件的樣式),這時(shí)候就需要 getComputedStyle
出場(chǎng)了.const element = document.getElementById('myElement');
const computedStyle = window.getComputedStyle(element);
console.log(computedStyle.width);
console.log(computedStyle.backgroundColor);
只讀:getComputedStyle
返回的對(duì)象是只讀的, 不能通過它修改樣式.
獲取所有屬性:它會(huì)返回元素所有 CSS 屬性的計(jì)算值, 即使你沒設(shè)置過.
包含最終值:比如你設(shè)置了width: 50%,
它會(huì)返回計(jì)算后的像素值.
實(shí)際應(yīng)用示例:
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) 現(xiàn)代 JavaScript 提供了強(qiáng)大的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');
性能更好: 瀏覽器可以優(yōu)化類名的變化
更易維護(hù): 樣式定義保持在 CSS 文件中
支持復(fù)雜樣式: 可以一次性應(yīng)用多個(gè)樣式規(guī)則
支持偽類和媒體查詢: 這些在 JavaScript 中無法直接設(shè)置
2) 一個(gè)實(shí)際應(yīng)用示例:
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');
});
});
四、有時(shí)候我們需要更動(dòng)態(tài)地控制樣式, 比如添加或修改整個(gè)樣式規(guī)則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);
五、現(xiàn)代 CSS-in-JS 方案簡(jiǎn)介隨著前端框架的流行,CSS-in-JS方案越來越受歡迎. 它們?cè)试S我們?cè)贘avaScript中編寫 CSS, 并提供了許多強(qiáng)大功能.
CSS-in-JS是一種將CSS直接寫在 JavaScript 文件中的技術(shù),它通常有以下特點(diǎn):
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}>點(diǎn)擊我</button>;
}
閱讀原文:原文鏈接
該文章在 2025/7/7 11:31:40 編輯過