简体   繁体   English

如何使用输入参数创建通用CSS类

[英]How to create generic CSS class with input parameter

I am showing list of items on UI. 我正在UI上显示项目列表。 Those items have attribute as tLevel. 这些项目的属性为tLevel。 Depending on tLevel value I want to create tree structure. 根据tLevel的值,我想创建树结构。

Something like this 像这样

item1                   tLevel=0
    item2               tLevel=1
        item3           tLevel=2    
    item4               tLevel=1
        item5           tLevel=2
            item6       tLevel=3    
            item7       tLevel=3
            item8       tLevel=3
item9                   tLevel=0
    item10              tLevel=1
    item11              tLevel=1

HTML template HTML模板

<div class="treeLevelCSS(' + tLevel + ')" />

CSS should be something like CSS应该像

.treeLevelCSS(tLevel){
    "margin-left: " + (tLevel * 15) + "px"
}

I am not sure what I have written above in HTML and CSS is right, but just to give an idea of what I want to achieve here. 我不确定我上面用HTML和CSS编写的内容是正确的,只是想对我想要在这里实现的内容有所了解。

If possible it might be beneficial to use nested lists here, with each level just having padding applied to it. 如果可能的话,在这里使用嵌套列表可能是有益的,每个级别仅对其应用填充即可。

For example: 例如:

<ul>
  <li>1</li>
  <li>
    <ul>
      <li>2</li>
      <li>
        <ul>
          <li>3</li>
        </ul>
      </li>
      <li>2</li>
    </ul>
  </li>
  <li>1</li>
</ul>

and... 和...

li {
  list-style:none;
}
ul ul {
  padding-left:20px;
}

Should do the job, demo: http://codepen.io/merlinmason/pen/vORaVB 应该做的事,演示: http : //codepen.io/merlinmason/pen/vORaVB

If you're using Less, what you need in a simplest case is a mixin and selector "interpolation" , eg: 如果您使用的是Less,那么在最简单的情况下,您需要的是mixin选择器“ interpolation” ,例如:

.treeLevel(0);
.treeLevel(1);
.treeLevel(2);
.treeLevel(3);

.treeLevel(@level) {
    .treeLevelCSS@{level} {
        margin-left: @level * 15px;
    }
}

Then, depending on your needs, get it further improved with other stuff. 然后,根据您的需求,将其与其他产品一起进一步改进。 For example using loops to reduce repetition and/or possibility to generate an arbitrary number of class. 例如,使用循环来减少重复和/或生成任意数量的类的可能性。 See native Less loops and/or a syntactic sugar goodies for those like .for : 请参阅原生的Less 循环和/或语法糖好吃的东西,例如.for

@import "for";

.tree-level- {
    // generate 8 level classes:
    .for(0, 7); .-each(@i) {
        &@{i} {
            margin-left: 15px * @i;
        }
    }
}

Codepen Demo for above (slightly modified) snippet. 上面(略有修改)代码段的Codepen演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM