Can you do a javascript for loop inside of LESS css?

我的未来我决定 提交于 2019-11-29 01:46:23

I will recommend to checkout Twitter Bootsrap. They are building their grid system that way. They loop, with recursion, in a less mixin, instead of typing every class they need.

The interesting part is in mixins.less file, in the less directory, below "// The Grid" comment (line 516). The interesting portion is:

#grid {

    .core (@gridColumnWidth, @gridGutterWidth) {

      .spanX (@index) when (@index > 0) {
        (~".span@{index}") { .span(@index); }
        .spanX(@index - 1);
      }
      .spanX (0) {}

      ...

      .span (@columns) {
        width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1));
      }
 ...

Which is called in grid.less file in less directory this way:

#grid > .core(@gridColumnWidth, @gridGutterWidth);

Which produce (among other things):

.span12 {
  width: 940px;
}
.span11 {
  width: 860px;
}
.span10 {
  width: 780px;
}
...

in bootstrap.css line 170.

For @gridColumnWidth, @gridGutterWidth and the rest of variables check variables.less file (line 184)

Be sure to have the last version of lessc node compiler installed.

There's nothing about loops in the docs, but since you can access JavaScript expressions via backticks, you could always define a function in your script (not your LESS code, but JavaScript — e.g., if in a browser, you'd have a separate script element) that does your loop and then access it, e.g.:

@height: `doMyLoop()`

It depends on what you're trying to achieve with the loop. If you want the loop to output CSS rules, I suspect you're out of luck.

This is a hack but... Add this to your less file.

@testColor: green;

unusedclass {
    unknownprop: ~`loopCss(10,".group{{i}} { background-color: @{testColor}; }")`
}

Create a javascript file loopCss.js with the following function:

function loopCss(count,cssTemplate) {
    // end the existing unused class
    var result = "0;}\n";
    // Add your custom css
    for(var i=0; i<count; i++) result += cssTemplate.replace("{{i}}",i) +"\n";
    // Handle the close bracket from unused class
    result += "unusedclass {";
    return result;
}

Now include the loopCss.js before your less.js and it should work.

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