简体   繁体   中英

Using a LESS @ variable in javascript

I am messing around with a custom html module which has the following code

<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;">

I am also using .less and have some custom variable (@color-1) which I would like to use instead with the data-fgcolor="#555" .

I have tried obviously replacing "#555" with "@color-1" which did not work. In my script.js I can also add the following to change the color:

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

However I am looking for a solution where by everytime the '@color-1:' value in my .less file is changed then the above 'data-fgcolor' is changed whether by the custom html module or through js.

Thanks.

You can't use LESS variables, or CSS in general, to modify html attributes. If you insist on having your fgcolor value reside in your LESS/CSS (as opposed to just being in your script), you're going to have to use a workaround. ie:

<!-- 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"/>

Then, wherever you're using the code you posted, you can do the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM