I have a colors.less
file that maintains consistent color palette for a site.
I also have a chart.js
file that requires hard coded colors to display chart elements in appropriate colors.
How can I make the chart colors dependent on the generated colors.css
file?
So far I've been maintaining two color palettes, one in less
and another in js
. How can I merge the two?
Example:
/* colors.less */
@green: #46a546;
@red: #9d261d;
@yellow: #f1c40f;
and
/* chart.js */
var chartElements = {
"apples": {
label: "Apples",
color: "#46a546",
},
"oranges": {
label: "Oranges",
color: "#f1c40f",
},
"grapes": {
label: "Grapes",
color: "#9d261d",
}...
How can I stop maintaining both sets of colors?
Even tho Pointy's answer may fit better here (talking about LESS), I want to remind that you can access stylesheet data directly via ECMAscript. You might be able to identify a specific rule and just grab the value. Might look like
[].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 );
}
});
}
});
Having that exact problem, I "solved" it with the following hack.
The CSS includes a list of "swatch-nn" classes ( swatch-1
, swatch-2
, and so on). Those get the pre-defined LESS constants as their background color. (For me, a simple numerically-ordered list works; other situations might call for other approaches.)
My SPA wrapper creates a (hidden) list of elements that have the swatch classes.
<div id=swatches> <div class=swatch-1> <div class=swatch-2> <!-- etc --> </div>
Some JavaScript code at application startup populates a globally-available list of colors from the swatches.
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;
My Chart.js code thus copies the color values out of that global array. It's crude but it works fine.
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.