在 javascript 中使用 LESS @ 变量

Using a LESS @ variable in javascript

本文关键字:LESS 变量 javascript      更新时间:2023-09-26

我正在弄乱一个自定义的html模块,该模块具有以下代码

<div id="circle1" class="circle-stat chart circliful" data-fill="transparent" data-bgcolor="#333" data-fgcolor="#555" data-percent="85" data-fontsize="38" data-width="20" data-text="85%" data-dimension="200" style="width: 200px;">

我也在使用 .less 并且有一些自定义变量 (@color-1(,我想将其与 data-fgcolor="#555" 一起使用。

我尝试明显地将"#555"替换为"@color-1",但不起作用。在我的脚本中.js我还可以添加以下内容来更改颜色:

jQuery(function($){
  $('.circle-stat').attr("data-fgcolor", "#555");
  $('.circle-stat').circliful();
});

但是,我正在寻找一种解决方案,每次更改我的 .less 文件中的"@color-1:"值时,无论是通过自定义 html 模块还是通过 js 更改上述"data-fgcolor"。

谢谢。

你不能使用 LESS 变量或一般的 CSS 来修改 html 属性。如果你坚持让你的fgcolor值驻留在你的LESS/CSS中(而不是仅仅在你的脚本中(,你将不得不使用一个解决方法。即:

<!-- this style will go in your less file -->
<style>
   .fgColorHere {
      color: @yourColorVariableGoesHere; // your desired color goes here
   }
</style>
<!-- you can just stick this element anywhere in the DOM -->
<!-- apply your color to this hidden element so we can grab the color value -->
<div id="workaroundElement" style="display: none" class="fgColorHere"/>

然后,无论您在哪里使用发布的代码,都可以执行以下操作:

jQuery(function($){
   var colorVal = $("#workaroundElement").css("color");
   $('.circle-stat').attr("data-fgcolor", colorVal);
   $('.circle-stat').circliful();
});