问题
Is there any option to insert some LESS mixin in to JS code?
I have this border-radius mixin:
.border_radius(@radius: 5px) {
border-radius: @radius;
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
}
So is there any possible to add this mixin in to jQuery code?
var less = require('less');
$('.circle').css({
width: width, height: width,
less.border_radius(10px);
});
回答1:
You could define the JavaScript equivalent of the LESS mixins you require:
HTML
<div class="circle"></div>
CSS
.circle { border: 1px solid #FF0000; }
jQuery
function border_radius(radius) {
radius = radius || '5px';
return {
'border-radius': radius,
'-moz-border-radius': radius,
'-webkit-border-radius': radius
}
}
var styles = border_radius(),
width = '20px';
styles.width = width;
styles.height = width;
$('.circle').css(styles);
JSFiddle
回答2:
This is not exactly what you wanted, but maybe this trick would be helpful. I do not see other way to use less's functions dynamically.
var parser = new less.Parser({});
var lessCode = '';
function roundedCorners(_class, radius) {
lessCode = '/* import dependent syles */'
+ '@import "PATH-TO-YOUR-MAIN-LESS-FILE";'
+ '.' + _class + ' {'
+ '.rounded-corners(' + radius + 'px);'
+ '}';
parser.parse(lessCode, function (error, root) {
$('head').append($( '<style type="text/css">' + root.toCSS() + '</style>' ));
});
}
//try...
roundedCorners('circle', 10);
来源:https://stackoverflow.com/questions/16336695/how-to-insert-less-mixin-in-to-javascript-code