亚洲乱色熟女一区二区三区丝袜,天堂√中文最新版在线,亚洲精品乱码久久久久久蜜桃图片,香蕉久久久久久av成人,欧美丰满熟妇bbb久久久

LOGO OA教程 ERP教程 模切知識(shí)交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

JavaScript 中的樣式與 CSS 操作

admin
2025年7月6日 14:14 本文熱度 805

今天我就來跟大家聊聊 JavaScript 中操作樣式的各種方法, 從最基礎(chǔ)的 style 屬性操作, 到現(xiàn)代 CSS-in-JS 方案,咱們一步步來.

一、最直接的方式-操作元素的style屬性
1)基本用法:
當(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 文件中的樣式.
2)注意事項(xiàng):
* 屬性名轉(zhuǎn)換:CSS 屬性中的連字符(如 background-color)在 JavaScript中要改為駝峰命名(backgroundColor).
* 單位不能少:像 widthheight、margin 這樣的屬性必須帶上單位:
//正確element.style.width = '100px';
//錯(cuò)誤-這樣不會(huì)生效element.style.width = 100;
* 批量設(shè)置: 可以用cssText一次性設(shè)置多個(gè)樣式:
element.style.cssText = 'width: 100px; height: 200px; background: red;';//這會(huì)覆蓋之前的所有內(nèi)聯(lián)樣式
3)一個(gè)實(shí)際應(yīng)用的場(chǎng)景,內(nèi)聯(lián)樣式最適合用在需要?jiǎng)討B(tài)計(jì)算的樣式上,比如:
//根據(jù)數(shù)據(jù)動(dòng)態(tài)設(shè)置進(jìn)度條寬度const progress = document.getElementById('progress');progress.style.width = `${currentProgress}%`;
//鼠標(biāo)跟隨效果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); //獲取計(jì)算后的寬度console.log(computedStyle.backgroundColor); //獲取計(jì)算后的背景色
特點(diǎn):

  • 只讀:getComputedStyle 返回的對(duì)象是只讀的, 不能通過它修改樣式.

  • 獲取所有屬性:它會(huì)返回元素所有 CSS 屬性的計(jì)算值, 即使你沒設(shè)置過.

  • 包含最終值:比如你設(shè)置了width: 50%, 它會(huì)返回計(jì)算后的像素值.


實(shí)際應(yīng)用示例:

//檢查元素是否隱藏function isHidden(element) {  return window.getComputedStyle(element).display === 'none';}
//獲取元素的實(shí)際寬度(包括padding和border)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');
//檢查是否包含某個(gè)類if (box.classList.contains('active')) {  console.log('元素有active類');}
//替換類box.classList.replace('old-class''new-class');
優(yōu)點(diǎn):

  • 性能更好: 瀏覽器可以優(yōu)化類名的變化

  • 更易維護(hù): 樣式定義保持在 CSS 文件中

  • 支持復(fù)雜樣式: 可以一次性應(yīng)用多個(gè)樣式規(guī)則

  • 支持偽類和媒體查詢: 這些在 JavaScript 中無法直接設(shè)置


2) 一個(gè)實(shí)際應(yīng)用示例:
//實(shí)現(xiàn)一個(gè)簡(jiǎn)單的選項(xiàng)卡切換const tabs = document.querySelectorAll('.tab');const panels = document.querySelectorAll('.panel');
tabs.forEach(tab => {  tab.addEventListener('click'() => {    //移除所有active類    tabs.forEach(t => t.classList.remove('active'));    panels.forEach(p => p.classList.remove('active'));
    //添加active類到當(dāng)前tab和對(duì)應(yīng)panel    tab.classList.add('active');    const panelId = tab.getAttribute('data-panel');    document.getElementById(panelId).classList.add('active');  });});
四、有時(shí)候我們需要更動(dòng)態(tài)地控制樣式, 比如添加或修改整個(gè)樣式規(guī)則
1) 創(chuàng)建新的樣式表:
const style = document.createElement('style');style.textContent = `  .highlight {    background-color: yellow;    border: 2px solid orange;  }`;document.head.appendChild(style);
2)修改現(xiàn)有的樣式表:
// 獲取第一個(gè)樣式表const stylesheet = document.styleSheets[0];
// 添加新規(guī)則stylesheet.insertRule('.error { color: red; }', stylesheet.cssRules.length);
// 刪除規(guī)則stylesheet.deleteRule(0); // 刪除第一條規(guī)則
五、現(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):

  • 局部作用域樣式(避免全局污染)

  • 自動(dòng)添加瀏覽器前綴

  • 支持基于props的動(dòng)態(tài)樣式

  • 自動(dòng)處理關(guān)鍵CSS和代碼分割


1) styled-components示例: 
import styled from 'styled-components';
//創(chuàng)建一個(gè)帶樣式的按鈕組件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>
2)Emotion示例:
/** @jsxImportSource @emotion/react */import { css } from '@emotion/react';
const style = css`  background: blue;  color: white;  padding10px 20px;
  &:hover {    opacity0.8;  }`;
function MyComponent() {  return <button css={style}>點(diǎn)擊我</button>;}


閱讀原文:原文鏈接


該文章在 2025/7/7 11:31:40 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對(duì)中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國(guó)內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對(duì)港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場(chǎng)、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場(chǎng)作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲(chǔ)管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購(gòu)管理,倉儲(chǔ)管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號(hào)管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved