Make fewer variables available from javascript?

I have fewer colors for files that look like this:

@black:                 #000;
@greyDarker:            #222;
...etc

And I want to have access to them from javascript, for example:

$('body').style('color', 'window.colours.black') // or however I assign them

will work.

Since Less gets the compiled server side, the usual options will not work.

I started to advance and wrote a grunt task to generate a js file from these smaller rules, but this seems like an inefficient / hacker way to do this.

Any suggestions for a better approach or tools that might help

+4
source share
3 answers

CSS . . - , div.less-rule- {rule-name}

.

div.less-rule-black {
    background-color: @black;
}
div.less-rule-grey-darker {
    background-color: @greyDarker;
}

JavaScript API . -. , .

var rules, rule, i, n, j, m, key;
var lessRules = [];
for (i = 0, n = document.styleSheets.length; i < n; i++) {
    rules = document.styleSheets[i].cssRules; 
    for (j = 0, m = rules.length; j < m; j++) {
        rule = rules[j];
        if (rules[j].selectorText.indexOf('less-rule') !== -1) {
           key = /div.less-rule-(.*)/.exec(rules[j].selectorText)[1];
           lessRules[key] = rule.style['background-color']; 
        }
    }
}

, .

console.log(lessRules['black']);
console.log(lessRules['grey-darker']);
+3

, , . CSS, javascript.

CSS

.black {color: #000;}
.greyDarker {color: #222;}

JavaScript:

$('body').addClass('black');

CSS, :

$('body').css('color', 'black');

, : http://www.crockford.com/wrrrld/color.html http://www.cssportal.com/css3-color-names/,


- , , Javascript javascript, .

+1

, LESS, CSS. getComputedStyle:

function getLessVariableValue(variable) {
    var elt = document.createElement('div');
    elt.className = variable+"-variable";
    elt.style.display= "none";        // ensure element is not visible
    document.body.appendChild(elt);   // elt must be in DOM to compute styles
    var result = window.getComputedStyle(elt).fontFamily;
    document.body.removeChild(elt);
    return result;
}

document.writeln(getLessVariableValue('purple'))
/* replace "purple" below with '@purple' etc. */
.purple-variable { font-family: purple; }
Hide result

We use font-familyit because it can take any arbitrary string as its value.

Alternatively, you can view the style rules for one s .purple-variableas a selector, as @Adam suggests in your answer. It seems a little more attractive to me.

However, it does seem like a lot of work to accomplish what? There may be better ways to accomplish what you are trying to do.

+1
source

All Articles