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");

五、使用 className 或 classList-添加一个预定义的 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;
}

六、使用 createElement 和 appendChild- 动态创建一个 <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>
相关推荐
Java后端的Ai之路32 分钟前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
船神丿男人1 小时前
从爬楼梯到最小路径和:6 道 C++ 动态规划题的状态设计
开发语言·c++·动态规划
Evand J1 小时前
【MATLAB例程】基于多基站AOA与距离辅助的二维运动目标定位及速度估计,附下载链接
开发语言·matlab·距离·aoa·多基站
GuWenyue1 小时前
昵称限 20 字,8 个 emoji 却超长:一个「字」在系统里有四种长度
javascript·数据库·后端
数字供应链安全产品选型1 小时前
从自动化扫描到 AI 自主攻防:下一代渗透测试需要突破哪些核心技术?
开发语言·php
赤生云电竞1 小时前
云电竞GPU虚拟化选型:vGPU与直通架构实践对比
java·开发语言·架构
吹什么轩2 小时前
c++高并发内存池(一):从objectpool到central cache
java·开发语言
汤姆宝库2 小时前
HNSW:分层图上的贪心检索
开发语言·python
GitCode官方3 小时前
本期精选 Rust 开源项目推荐
开发语言·rust·开源·g-star·atomgit
Pin_Qing3 小时前
当旗舰模型挂上 Flash 的价签:MiniMax M4 的定价逻辑与工程账本
服务器·开发语言·网络·人工智能·程序人生