How to insert LESS mixin in to JavaScript code

社会主义新天地 提交于 2019-12-12 10:14:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!