JavaScript 写css的内联样式

**一、使用style属性-**直接设置单个 CSS 属性

javascript 复制代码
// 获取元素
var element = document.getElementById("myElement");

// 设置样式
element.style.color = "red";
element.style.backgroundColor = "blue";
element.style.fontSize = "20px";

**二、使用cssText属性-**一次性设置多个 CSS 属性

javascript 复制代码
// 获取元素
var element = document.getElementById("myElement");

// 设置样式
element.style.cssText = "color: red; background-color: blue; font-size: 20px;";

**三、使用setAttribute方法-**通过设置 style 属性来添加样式

javascript 复制代码
// 获取元素
var element = document.getElementById("myElement");

// 设置样式
element.setAttribute("style", "color: red; background-color: blue; font-size: 20px;");

**四、使用setProperty方法-**设置 CSS 属性,并可以选择设置优先级(如 important

javascript 复制代码
style.setProperty(propertyName, value, priority);
  1. propertyName : 要设置的 CSS 属性名称(例如 'color''background-color')。
  2. value : 属性的值(例如 'red''16px')。
  3. priority (可选): 优先级标志 ,通常是 'important'。如果不指定,默认为空字符串,表示没有优先级。
javascript 复制代码
// 获取元素
var element = document.getElementById("myElement");

// 设置样式
element.setProperty("color", "red","important");

五、使用 classNameclassList-添加一个预定义的 CSS 类

javascript 复制代码
// 获取元素
var element = document.getElementById("myElement");

// 使用className添加
element.className = 'myClass';

// 添加CSS类
element.classList.add("myClass");

// 移除CSS类
element.classList.remove("myClass");
css 复制代码
.myClass {
    color: red;
    background-color: blue;
    font-size: 20px;
}

六、使用 createElementappendChild- 动态创建一个 <style> 元素并添加 CSS 类

javascript 复制代码
const style = document.createElement('style');
style.textContent = `
  .myClass {
    color: red;
    font-size: 20px;
  }
`;
document.head.appendChild(style);

七、使用 insertAdjacentHTML- 使用 insertAdjacentHTML 方法插入 CSS

javascript 复制代码
element.insertAdjacentHTML(position, text);
  1. position: 插入内容的位置,可以是以下四个字符串之一:
    1. 'beforebegin': 在目标元素之前插入。
    2. 'afterbegin': 在目标元素的第一个子节点之前插入。
    3. 'beforeend': 在目标元素的最后一个子节点之后插入。
    4. 'afterend': 在目标元素之后插入。
  2. text: 要插入的 HTML 字符串。
javascript 复制代码
document.head.insertAdjacentHTML('beforeend', `
  <style>
    .myClass {
      color: red;
      font-size: 20px;
    }
  </style>
`);

八、使用 innerHTML- 动态创建一个 <style> 元素并通过 innerHTML 设置 CSS

javascript 复制代码
const style = document.createElement('style');
document.head.appendChild(style);
style.innerHTML = `
  .myClass {
    color: red;
    font-size: 20px;
  }
`;

九、使用CSSStyleSheet - 动态创建一个 <style> 元素并通过 CSSStyleSheet 插入 CSS 规则

javascript 复制代码
stylesheet.addRule(selector, style, index);
  1. selector : CSS 选择器(例如 '.my-class')。
  2. style : CSS 样式声明字符串(例如 'color: red; font-size: 20px;')。
  3. index(可选): 规则在样式表中的位置。如果不指定,默认添加到最后。
javascript 复制代码
stylesheet.insertRule(rule, index);
  1. rule : 包含选择器和样式声明的完整 CSS 规则字符串(例如 '.my-class { color: red; font-size: 20px; }')。
  2. index(可选): 规则在样式表中的位置。如果不指定,默认添加到最后。
javascript 复制代码
// 创建一个新的样式表
const styleSheet = document.createElement('style');
document.head.appendChild(styleSheet);

// 获取样式表的 sheet 对象
const sheet = styleSheet.sheet;

// 添加一条 CSS 规则
sheet.insertRule('.my-class { color: red; }', sheet.cssRules.length);

十、使用 window.getComputedStyle 查询计算后的样式-查询计算后的样式

javascript 复制代码
// 获取元素
var element = document.getElementById("myElement");

// 设置样式
element.style.color = "red";
element.style.backgroundColor = "blue";
element.style.fontSize = "20px";


 // 查询计算后的样式
 const computedStyle = window.getComputedStyle(element);
 console.log(computedStyle.color); // 输出:red
 console.log(computedStyle.backgroundColor); // 输出: blue
 console.log(computedStyle.fontSize); // 输出: 20px

综合应用

javascript 复制代码
<template>
  <div id="myElement">myElement</div>
</template>

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  // 获取元素
  var element = document.getElementById("myElement");

  // 使用style属性设置样式
  element.style.color = "red";
  element.style.backgroundColor = "blue";
  element.style.fontSize = "20px";

  // 使用cssText属性设置样式
  element.style.cssText += " border: 10px solid black;";

  // 使用setAttribute方法设置样式
  element.setAttribute("style", element.getAttribute("style") + " padding: 100px;");

  // 使用setProperty方法设置样式
  element.style.setProperty("margin", "50px", "important");

  // 使用className或classList添加CSS类
  element.classList.add("myClass");

  // 定义一个CSS类
  const style = document.createElement('style');
  style.textContent = `
    .myClass {
      color: green;
      background-color: yellow;
      font-size: 24px;
    }
  `;
  document.head.appendChild(style);

  // 使用insertAdjacentHTML插入CSS
  document.head.insertAdjacentHTML('beforeend', `
    <style>
      .anotherClass {
        color: purple;
        font-size: 18px;
      }
    </style>
  `);

  // 使用innerHTML插入CSS
  const anotherStyle = document.createElement('style');
  document.head.appendChild(anotherStyle);
  anotherStyle.innerHTML = `
    .yetAnotherClass {
      color: orange;
      font-size: 22px;
    }
  `;

  // 使用CSSStyleSheet插入规则
  const styleSheet = document.createElement('style');
  document.head.appendChild(styleSheet);
  const sheet = styleSheet.sheet;
  sheet.insertRule('.dynamicClass { color: brown; font-size: 26px; }', sheet.cssRules.length);

  // 查询计算后的样式
  const computedStyle = window.getComputedStyle(element);
  console.log(computedStyle.color); // 输出:rgb(0, 128, 0) (green)
  console.log(computedStyle.backgroundColor); // 输出:rgb(255, 255, 0) (yellow)
  console.log(computedStyle.fontSize); // 输出:24px
  console.log(computedStyle.margin); // 输出:5px (important)
});
</script>

<style></style>
相关推荐
名字还没想好☜2 小时前
React 实现暗黑模式切换:localStorage 持久化、SSR 首屏闪烁与跟随系统主题
前端·javascript·react.js·ecmascript·react·next.js
kruptos2 小时前
分布式系统怎么“选主“?Raft 共识一次讲清
开发语言·分布式·php·共识算法
吴声子夜歌3 小时前
ApacheCommons——commons-cli(命令行参数解析)
java·开发语言·apache
自动化监测Learner3 小时前
主流 Web 端地图引擎对比:选型指南与优劣分析
javascript
benchmark_cc4 小时前
REST API 和 Python SDK 应该怎么选?量化交易数据接口选型实战
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
王的宝库4 小时前
Go 项目结构:从单文件到标准工程布局
开发语言·后端·golang
Tairitsu_H4 小时前
[C++] 深入理解红黑树:封装set与map
开发语言·c++·set·map·红黑树·模拟实现
泡海椒4 小时前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp
小智老师PMP4 小时前
2026深度解析|PMP第八版与NPDP核心侧重点本质区别(管理类证书怎么选)
开发语言·分布式·算法·职场和发展·产品经理
江畔柳前堤5 小时前
前台·中台·后台:2026年AI原生时代的架构全景图
开发语言·人工智能·算法·机器学习·架构·scala·ai-native