最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Make less variables accessible from javascript? - Stack Overflow

programmeradmin0浏览0评论

I have a less file colours which defines looks like the following:

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

And want to be able to access these from within javascript, so for example:

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

would work.

Since Less is getting compiled server-side the usual options wouldn't work.

I've started going ahead and writing a grunt task to generate a js file from these less rules however this seems like an inefficient / hacky way to go about it.

Any suggestions on a better approach or tools that could help

I have a less file colours which defines looks like the following:

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

And want to be able to access these from within javascript, so for example:

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

would work.

Since Less is getting compiled server-side the usual options wouldn't work.

I've started going ahead and writing a grunt task to generate a js file from these less rules however this seems like an inefficient / hacky way to go about it.

Any suggestions on a better approach or tools that could help

Share Improve this question asked Oct 14, 2014 at 5:41 iosephioseph 1,91721 silver badges26 bronze badges 2
  • Did any of these answers work for you? If so, please accept. – user663031 Commented Oct 28, 2014 at 14:34
  • Do you have any results worth mentioning from your grunt task? I am currently thinking about the same issue - making less variables (mainly resolution-specific breakpoints) known in JS. In my case, I'd prefer a build task, grunt, gulp or something which I can integrate into our project build – Windwalker Commented Jan 19, 2016 at 23:08
Add a comment  | 

4 Answers 4

Reset to default 6

You could put some special definitions in your CSS to pass through the definitions. These would only be used to pass the variables and nothing else. You'd need to come up with some convention, here I've used div.less-rule-{rule-name}

For example.

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

You could then pick these up using the JavaScript API for accessing stylesheets. You could put this in a utility class somewhere. This only needs to be done once when all the stylesheets are loaded.

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']; 
        }
    }
}

You can then access the variables by using the key in the hash.

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

You can use css variables Like

let StyleVars = document.querySelector(':root');
// Create a function for getting a variable value
function GetStyleVars(Variable = "--color" ) {
  // Get the styles (properties and values) for the root
    var Style = getComputedStyle(StyleVars);
    return(Style.getPropertyValue(Variable));
}
// Create a function for setting a variable value
function ChangeVariableValue(Value,Variable = "--color") {
  // Set the value of variable to another Value
  StyleVars.style.setProperty(Variable, Value);
}


document.getElementById("A").onclick = function(){
ChangeVariableValue('red');
}



document.getElementById("B").onclick = function(){
ChangeVariableValue('green');
}


document.getElementById("C").onclick = function(){
ChangeVariableValue('black');
}


document.getElementById("D").onclick = function(){
alert(GetStyleVars());
}
:root{
 --color : #fff;
}
button{
border :2px solid var(--color);
}
<button id="A">Red</button>
<br>
<button id="B">Green</button>
<br>
<button id="C">Black</button>
<br>
<button id="D">Alert Value</button>

First add a rule using the LESS variable to your CSS. Then create a dummy element with that class, and examine its getComputedStyle color:

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

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

Alternatively, you could look through the style rules for the one with .purple-variable as a selector, as @Adam suggests in his answer. To me that seems a bit more involved.

However, this seems like a lot of work to go to, to accomplish--what? There may be better ways to accomplish what you are trying to do.

You can attach each color to a class name in your style rules and then add a particular class to your object to trigger the setting of the desired color. The class names would be defined in your CSS styles and then you just refer to them by string name in your javascript.

CSS:

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

Javascript:

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

You can also use the CSS color names built into the browser:

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

Here's a list of color names built in: http://www.crockford.com/wrrrld/color.html and http://www.cssportal.com/css3-color-names/,


Other than something like this, if you want programmatic access to symbolic names for colors, then you will need to generate your own Javascript definitions for the names and include that in your javascript where you can use those symbols.

发布评论

评论列表(0)

  1. 暂无评论