Is Javascript Evaluation working in LESS (Leaner C

2019-08-29 19:31发布

问题:

I am using LESS ( http://lesscss.org ) and it says ...

JavaScript evaluation

JavaScript expressions can be evaluated as values inside .less files. This is done by wrapping the expression with back-ticks:

The example provided is ...

@height: `document.body.clientHeight`;

So I've tried to do this in my html ...

<script type="text/javascript">
    var fred=5;
</script>
<link rel="stylesheet/less" type="text/css" href="styles.less">
<script type="text/javascript" src="http://lesscss.googlecode.com/files/less-1.2.1.min.js"></script>     

and this in styles.less ...

@height:`fred + "px"`;

.mydiv {
    background-color:green;
    height:@height;
}

But it just won't work! Also tried variations on this such as using ...

@height:`fred`px;
@height:`fred`;

If I use ...

@height:20px;

It works as expected but I need to use Javascript evaluation. I would really appreciate it if someone could help - Answers focusing on answering the question and not asking why I need to use Javascript evaluation would be greatly appreciated. Thanks very much all

Its worth noting that if I do ...

@height:`freddd`px;

where freddd is undefined, I get an error from the less compiler - hence it seems to know that fred is defined. However, currently I am not getting an error - it is just not doing anything when I use Javascript variable values.

回答1:

I am working on the same thing. The way I have been testing the expression is to compile the less file in the browser as you are doing (I am using firefox with firebug). I inspect my rendered css by inspecting the head section of the rendered page and looking for <style id="less:yourLessFileName-less-styles" type="text/css"> . Twirl that file open and you will see the compliled css. Scroll down until you find your selector and rule you are using the javascript expression for and see how it rendered.



回答2:

You probably can't call variables created in JS. From what I understand, JavaScript expressions can be evaluated means just that you can evaluate stuff with JS functions and use default JS objects like document.body.clientHeight which doesn't mean that you can call variables from a different file and location. It just doesn't make sense that it'll let you do that, how is it supposed to find the variable?. I might be wrong tho..