问题
I am showing list of items on UI. Those items have attribute as tLevel. Depending on tLevel value I want to create tree structure.
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
<div class="treeLevelCSS(' + tLevel + ')" />
CSS should be something like
.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.
回答1:
If you're using Less, what you need in a simplest case is a mixin and selector "interpolation", e.g.:
.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:
@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.
回答2:
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
来源:https://stackoverflow.com/questions/31275436/how-to-create-generic-css-class-with-input-parameter