如何有效地将 css 值导入 javascript 文件?

How can I efficiently import css values into javascript file?

我有一个 colors.less 文件,可以为网站维护一致的调色板。

我还有一个 chart.js 文件,该文件需要硬编码颜色才能以适当的颜色显示图表元素。

如何使图表颜色依赖于生成的 colors.css 文件?

到目前为止,我一直在维护两个调色板,一个在 less 中,另一个在 js 中。如何合并两者?

示例:

/* colors.less */
@green:    #46a546;
@red:      #9d261d;
@yellow:   #f1c40f;

/* chart.js */
var chartElements = {
    "apples": {
        label: "Apples",
        color: "#46a546",
    },
    "oranges": {
        label: "Oranges",
        color: "#f1c40f",
    },
    "grapes": {
        label: "Grapes",
        color: "#9d261d",
    }...

如何停止维护两组颜色?

有那个确切的问题,我 "solved" 用下面的技巧解决它。

  1. CSS 包括 "swatch-nn" 类 的列表(swatch-1swatch-2 等)。那些获得预定义的 LESS 常量作为它们的背景颜色。 (对我来说,一个简单的数字排序列表是可行的;其他情况可能需要其他方法。)

  2. 我的 SPA 包装器创建了一个(隐藏的)元素列表,这些元素具有样本 类.

    <div id=swatches>
      <div class=swatch-1>
      <div class=swatch-2>
      <!-- etc -->
    </div>
    
  3. 一些 JavaScript 应用程序启动时的代码会从样本中填充全局可用的颜色列表。

    var swatches = {}, $swatchContainer = $("#swatches"), rname = /\bswatch-(.*)\b/;
    
    $swatchContainer.children("div").each(function() {
        var swatch = this;
        this.className.replace(rname, function(_, label) {
            swatches[label] = $(swatch).css("backgroundColor");
        });
    })
    
    $.swatches = swatches;
    

我的 Chart.js 代码因此从该全局数组中复制了颜色值。虽然简陋,但效果很好。

即使 Pointy 的答案在这里可能更合适(谈论 LESS),我想提醒您可以通过 ECMAscript 直接访问 stylesheet 数据。您可能能够识别特定规则并获取值。可能看起来像

[].forEach.call(document.styleSheets, function( set ) {
  if( set.href && set.href.indexOf( 'dialog.css' ) > -1 ) {
    [].forEach.call( set.cssRules, function( rule ) {
      if( rule.selectorText === 'div#dialog-container-left' ) {
        // to whatever here, grab the value and store it for global application usage
        console.log( rule.style.backgroundColor );
      }
    });
  }
});