【问题标题】:Extract colors from css从css中提取颜色
【发布时间】:2021-05-14 11:57:48
【问题描述】:

我需要从 CSS 中提取颜色。颜色有 3 种格式:

.style1 {
  color: #000;
}

.style2 {
  color: rgb(205, 92, 92)
}

.style3 {
  color: rgba(0, 0, 0, 0.5)
}

我有这个脚本(来自旧网页): https://jsfiddle.net/fekula/54kcxu1a/5/

但我只获得十六进制颜色。 不显示 rgb 和 rgba。

任何想法或一些类似的 javascript 用于提取和显示十六进制和 rgb/gba 颜色?

谢谢。

【问题讨论】:

  • 当您甚至没有为此类定义指定属性时,rgb()rgba() 是否正确的 css 语法?在第一个示例中,您指定“颜色”,这将是类的文本颜色。在后两个中,你没有。
  • 你是对的,谢谢。修改后的代码..
  • 您可以将十六进制转换为十进制。 RRGGBB 其中每个 RR,GG,BB 是一个两位十六进制数。如果那没有显示,我不确定是否要抓住“alpha”
  • 您打算从哪里提取这些颜色?它们可以在<style> 内部,或者任何元素的内联样式,或者在<link> 中引用。
  • 外部 CSS 文件。复制粘贴

标签: javascript jquery css colors


【解决方案1】:

您可以使用window.getComputedStyle()从元素中获取所有样式
示例:

let element = document.querySelector('.class');

let styles = window.getComputedStyle(element);

您的导航器控制台中的实验是支持 JavaScript,如 Chrome 和 Firefox。

获取页面的任何元素,并探索.getComputedStyle(...) 函数属性。

  • getComputedStyle 只给 rgb。

另一种方法是使用函数 convert 像这样转换为你:

https://www.phpied.com/rgb-color-parser-in-javascript/

【讨论】:

    【解决方案2】:

    任何...用于提取和显示十六进制和 rgb/gba 颜色 [来自 CSS 文件] 的 javascript?

    您可以使用String.prototype.matchAll() 来定位 CSS 规则字符串中的所有 hex、rgb() 和 rgba() 实例。

    const cssStr = `
    .style1 {
      color: #000;
    }
    
    .style2 {
      color: rgb(205, 92, 92)
    }
    
    .style3 {
      color: rgba(0, 0, 0, 0.5)
    }
    `;
    
    const regexHex = /#[A-Fa-f0-9]*/g;
    const hexs = [...cssStr.matchAll(regexHex)].flat();
    const regexRgb = /rgb\([0-9, ]*\)/g;
    const rgbs = [...cssStr.matchAll(regexRgb)].flat();
    const regexRgba = /rgba\([0-9, .]*\)/g;
    const rgbas = [...cssStr.matchAll(regexRgba)].flat();
    const colors = {
      hex: [...hexs],
      rgb: [...rgbs],
      rgba: [...rgbas]
    };
    console.log('colors:', colors);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2011-04-14
      • 2011-05-09
      • 2019-02-16
      • 2018-05-03
      • 1970-01-01
      • 2021-08-01
      • 2012-08-15
      相关资源
      最近更新 更多