Can less.js read class names and parameters from HTML?

扶醉桌前 提交于 2019-11-27 04:54:37

问题


I've just started using LESS and I love it. I'm now looking into grid.less which creates grids using LESS semantics.

This enables me to do something like this

//css
.mydiv { .column(9); }

//html
<div class="mydiv"> 9 column wide</div>

I've not studied less.js, but is there somehow possible to do the following:

//html
<div class="column(9)"> 9 column wide</div>

Is there any way to achieve this?


回答1:


LESS cannot easily read a parameter from the HTML, as LESS is a preprocessor (it processes the CSS before anything is presented in HTML). However, you can prebuild classes that will essentially do the same thing. You just need to set a practical limit to how many columns wide something might be. My example here is modest (5 columns max), but easily changed with the variable parameter. It uses a loop structure in LESS to build up to the maximum number of column classes you desire:

LESS

@numColClasses: 5;

.buildColumnClasses(@colNum) when (@colNum =< @numColClasses) {
  .column@{colNum} {
      .column(@colNum);
  }
  .buildColumnClasses((@colNum + 1));
}
//end loop
.buildColumnClasses(@colNum) when (@colNum > @numColClasses) {}

//start loop
.buildColumnClasses(1);

(Pseudo) CSS Output

.column1 {
  code-for-columns-at: 1 wide;
}
.column2 {
  code-for-columns-at: 2 wide;
}
.column3 {
  code-for-columns-at: 3 wide;
}
.column4 {
  code-for-columns-at: 4 wide;
}
.column5 {
  code-for-columns-at: 5 wide;
}

Use in HTML much like you were noting

<div class="column5"> 5 column wide</div>


来源:https://stackoverflow.com/questions/17104746/can-less-js-read-class-names-and-parameters-from-html

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