javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS动态添加style样式

JS动态添加style样式常用方法(附详细代码)

作者:藤原とラふ店丶

在JavaScript中,动态设置样式style是一种常见的操作,它允许开发者在运行时改变元素的外观,这篇文章主要介绍了JS动态添加style样式常用方法的相关资料,需要的朋友可以参考下

前言

在 JavaScript 中动态添加样式,核心是操作 DOM 元素的内联样式动态创建/修改样式表(<style> 标签),适用于单个元素样式调整、全局样式批量生效等场景。以下是常用方法,含详细示例和注意事项,同时适配 Vue3 setup 语法场景:

一、核心方法分类(按使用场景)

方法 1:操作单个元素的内联样式(优先级最高,仅作用于当前元素)

通过 element.style 直接设置样式,支持单个属性赋值、批量设置,适合精准控制单个元素。

1.1 直接设置单个样式(驼峰命名)

style 对象的属性需用 驼峰命名(如 backgroundColor 对应 CSS 的 background-color),优先级高于外部样式表。

// 获取目标元素(DOM 原生获取或 Vue3 ref 引用)
const targetEl = document.getElementById('box');
// 或 Vue3 setup 中用 ref:const targetEl = ref(null); 需在 onMounted 中访问 targetEl.value

// 单个样式赋值
targetEl.style.width = '300px';
targetEl.style.height = '200px';
targetEl.style.backgroundColor = '#f0f0f0';
targetEl.style.border = '1px solid #ddd';
targetEl.style.fontSize = '16px';

1.2 批量设置样式(用Object.assign)

适合一次性设置多个样式,代码更简洁:

const targetEl = document.querySelector('.content');
Object.assign(targetEl.style, {
  width: '500px',
  margin: '20px auto',
  padding: '15px',
  color: '#333',
  borderRadius: '8px',
  boxShadow: '0 2px 8px rgba(0,0,0,0.1)' // CSS3 样式同样支持
});

1.3 移除单个样式

通过 style.removeProperty('属性名') 或赋值为空字符串:

// 方式 1:removeProperty(需用 CSS 原生命名,如 background-color)
targetEl.style.removeProperty('background-color');

// 方式 2:赋值为空字符串(更简洁)
targetEl.style.border = '';

方法 2:动态创建<style>标签(全局样式,作用于所有匹配元素)

通过创建 <style> 标签并插入到 <head> 中,适合批量生效的全局样式(如主题切换、批量组件样式调整),支持 CSS 选择器、媒体查询等。

2.1 基础示例:添加全局样式

// 1. 创建 style 标签
const styleEl = document.createElement('style');
styleEl.type = 'text/css'; // 可选,现代浏览器默认支持

// 2. 编写 CSS 内容(支持所有 CSS 语法)
const cssContent = `
  .dynamic-class {
    color: #1E9FFF;
    font-weight: 600;
    transition: all 0.3s ease;
  }
  .dynamic-class:hover {
    color: #009688;
    transform: translateY(-2px);
  }
  /* 支持媒体查询 */
  @media (max-width: 768px) {
    .dynamic-class {
      font-size: 14px;
    }
  }
`;

// 3. 将 CSS 内容插入 style 标签
styleEl.textContent = cssContent;

// 4. 插入到 <head> 中(生效)
document.head.appendChild(styleEl);

// (可选)保存 style 标签引用,后续可删除
window.dynamicStyle = styleEl;

2.2 移除动态创建的全局样式

// 从 head 中移除 style 标签,样式立即失效
document.head.removeChild(window.dynamicStyle);

2.3 动态修改已有全局样式

通过修改 <style> 标签的 textContent 实现:

// 基于上面创建的 styleEl,修改 CSS 内容
styleEl.textContent = `
  .dynamic-class {
    color: #ff5722; /* 修改颜色 */
    font-size: 18px;
  }
`;

方法 3:修改已有样式表的规则(精确控制现有样式表)

如果页面已存在 <style> 标签或外部样式表,可通过 document.styleSheets 访问并修改其样式规则,适合微调现有样式。

示例:修改现有样式表的规则

// 1. 获取页面第一个样式表(可通过 index 或 href 筛选)
const styleSheet = document.styleSheets[0];

// 2. 新增样式规则(参数:选择器、样式内容、插入位置)
// 语法:insertRule(rule, index)
styleSheet.insertRule(`
  .box {
    background: #f5f5f5;
    padding: 20px;
  }
`, styleSheet.cssRules.length); // 插入到样式表最后

// 3. 修改已有规则(假设第 0 条规则是 .box)
const targetRule = styleSheet.cssRules[0];
targetRule.style.backgroundColor = '#eee'; // 直接修改属性
targetRule.style.padding = '25px';

// 4. 删除规则
styleSheet.deleteRule(0); // 删除第 0 条规则

二、Vue3setup语法中的特殊用法

在 Vue3 setup 中,需结合 ref(获取 DOM 元素)、onMounted(确保 DOM 渲染完成)等组合式 API 使用,避免操作未渲染的 DOM。

示例 1:Vue3 中给单个元素动态加内联样式

<template>
  <div ref="boxRef" class="box">Vue3 动态样式示例</div>
  <button @click="addDynamicStyle">添加样式</button>
</template>

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

// 1. 引用 DOM 元素
const boxRef = ref(null);

// 2. 确保 DOM 挂载后再操作(onMounted 中)
onMounted(() => {
  // 初始样式(可选)
  if (boxRef.value) {
    boxRef.value.style.opacity = '0.8';
  }
});

// 3. 点击按钮动态添加样式
const addDynamicStyle = () => {
  const box = boxRef.value;
  if (!box) return;

  Object.assign(box.style, {
    width: '400px',
    height: '200px',
    backgroundColor: '#1E9FFF',
    color: '#fff',
    borderRadius: '8px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  });
};
</script>

示例 2:Vue3 中动态创建全局样式(如主题切换)

<template>
  <button @click="switchTheme('light')">浅色主题</button>
  <button @click="switchTheme('dark')">深色主题</button>
  <div class="theme-container">主题测试内容</div>
</template>

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

// 存储全局样式标签引用,用于卸载时清理
let themeStyleEl = null;

// 切换主题(动态创建全局样式)
const switchTheme = (theme) => {
  // 先移除旧主题样式(避免冲突)
  if (themeStyleEl) {
    document.head.removeChild(themeStyleEl);
  }

  // 创建新样式标签
  themeStyleEl = document.createElement('style');
  const themeCss = theme === 'dark' 
    ? `
      .theme-container {
        background: #121212;
        color: #fff;
        border: 1px solid #333;
      }
      body { background: #000; }
    `
    : `
      .theme-container {
        background: #fff;
        color: #333;
        border: 1px solid #eee;
      }
      body { background: #f9f9f9; }
    `;

  themeStyleEl.textContent = themeCss;
  document.head.appendChild(themeStyleEl);
};

// 组件卸载时清理样式(避免内存泄漏)
onUnmounted(() => {
  if (themeStyleEl) {
    document.head.removeChild(themeStyleEl);
  }
});
</script>

三、关键注意事项

  1. 样式优先级:内联样式(element.style)> 动态 <style> 标签 > 外部样式表(按加载顺序),需注意冲突问题;
  2. 命名规范element.style 中 CSS 属性需用 驼峰命名(如 fontSize 而非 font-size),直接写 CSS 原生命名需用字符串(如 style['font-size'] = '16px');
  3. !important 用法:内联样式无法直接写 !important,需用 setProperty 方法:
    targetEl.style.setProperty('color', 'red', 'important');
    
  4. 内存泄漏:动态创建的 <style> 标签或事件绑定,需在组件卸载/不需要时手动移除(如 Vue3 onUnmounted 中清理);
  5. 兼容性:现代浏览器均支持上述方法,若需兼容 IE 需注意:styleSheet.cssRules 在 IE 中是 styleSheet.rules,可通过判断兼容:
    const cssRules = styleSheet.cssRules || styleSheet.rules;
    

四、常见场景总结

场景推荐方法
单个元素样式调整element.styleObject.assign
全局样式批量生效动态创建 <style> 标签
修改现有样式表规则document.styleSheets 操作规则
Vue3 组件内样式调整ref 获取元素 + 内联样式
主题切换/全局样式切换动态创建 <style> 标签(配合卸载清理)

总结

到此这篇关于JS动态添加style样式常用方法的文章就介绍到这了,更多相关JS动态添加style样式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文