You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用原生JavaScript将CSS规则以行内形式注入对应元素?

首先需要明确:行内样式不支持:hover这类CSS伪类选择器,所以如果你的需求包含伪类样式,还是需要通过注入<style>标签的方式实现;如果是普通的非伪类样式,可以直接遍历选中元素设置行内样式。

方案1:支持:hover等伪类的原生实现(符合你的示例需求)

直接在my-scripts.js中写入以下代码即可,无需jQuery,DOM加载完成后会自动生效:

// 等待DOM结构加载完成后自动执行逻辑
document.addEventListener('DOMContentLoaded', function () {
  // 原生实现CSS规则注入
  function injectStyles(cssRule) {
    const styleElement = document.createElement('style');
    styleElement.textContent = cssRule;
    document.head.appendChild(styleElement);
  }

  // 注入你需要的CSS规则
  injectStyles('.one .two a:hover { color: red; }');
});

方案2:普通样式设置为纯行内样式

如果你要设置的是元素默认状态的普通样式,不需要伪类,可以用以下方式直接设置行内样式:

document.addEventListener('DOMContentLoaded', function () {
  // 选中所有匹配选择器的目标元素
  const targetElements = document.querySelectorAll('.one .two a');
  // 遍历每个元素设置行内样式
  targetElements.forEach(el => {
    el.style.fontSize = '16px';
    el.style.color = '#222';
    // 更多样式可按上述格式依次添加
  });
});

内容的提问来源于stack exchange,提问作者SR Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:30:04