简体   繁体   English

将CSS应用于具有变量名的类

[英]Applying CSS on class with variable name

I'm generating class name from server side like: 我正在从服务器端生成类名,例如:

<p class="level_1">List item 1</p>
<p class="level_2">List item 2</p>
<p class="level_3">List item 3</p>
<p class="level_1">List item 1</p>
<p class="level_2">List item 2</p>
<p class="level_1">List item 1</p>

and I expect the output with indentation such that it looks like: 并且我期望带有缩进的输出看起来像:

List item 1
   List item 2
      List item 3
List item 1
   List item 2
List item 1

The syntax for class name is like level_$i where $i is variable and it can go to any level (starting from 1 to n). 类名的语法类似于level_$i ,其中$i是可变的,它可以进入任何级别(从1到n)。 So how can I apply CSS for indentation in this situation? 那么在这种情况下如何应用CSS进行缩进呢?

You can't do for loops in pure CSS. 您不能在纯CSS中进行for循环。 Consider using LESS for that purpose. 考虑为此目的使用LESS Here's a tutorial on LESS Loops 这是关于LESS 循环的教程

You can achieve this using jQuery ... see the jsFiddle example I prepared for you. 您可以使用jQuery来实现这一点...请参阅我为您准备的jsFiddle示例

var i= 1,
    val= 0;

$('[class^=level_]').each(function(){

$('.level_' + i).css('padding-left',val+'px');
    i++;
    val += 20;
});

I can see 2 solutions: 我可以看到2个解决方案:

  1. You can generate CSS style automatically while you are generating list (using PHP) 您可以在生成列表时自动生成CSS样式(使用PHP)
  2. You can use javascript/jquery to parse elements and create appropriate rules dynamically. 您可以使用javascript / jquery解析元素并动态创建适当的规则。 Here's JSBin: http://jsbin.com/zaviqeyavico/1/edit 这是JSBin: http//jsbin.com/zaviqeyavico/1/edit

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

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