首页 > 解决方案 > 如何根据 CSS 类的值动态应用填充值?

问题描述

我有一个名为“depth-0”的父类,它动态包含“depth-1”和“depth-2”我想要的是动态捕获该数字并与 padding-left 相乘

.depth-1 {
  padding-left: 15px;
}

.depth-2 {
  padding-left: 30px;
}

.depth-3 {
  padding-left: 45px;
}

.depth-4 {
  padding-left: 60px;
}

.depth-5 {
  padding-left: 75px;
}

.depth-6 {
  padding-left: 90px;
}

.depth-7 {
  padding-left: 105px;
}

.depth-8 {
  padding-left: 120px;
}

.depth-9 {
  padding-left: 135px;
}

.depth-10 {
  padding-left: 150px;
}

我想

.depth-n {
    padding-left: calc (n * 15px)
}

其中“n”是任意数字。

标签: csscss-selectors

解决方案


我们可以使用周围的方法来实现您正在寻找的东西,如下所示:

div{
    padding-left: calc(15px * var(--depth));
    margin-bottom: 3px;
}
<div style="--depth:1">a</div>
<div style="--depth:2">a</div>
<div style="--depth:3">a</div>
<div style="--depth:4">a</div>

或者,您也可以使用jQuery实现此目的:

$("[class^=depth-]").each(function(){
   $(this).css('padding-left',($(this).attr('class').match(/(?:^|\s)depth-(\d+)(?:$|\s)/)[1]*15) + "px");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="depth-0">0</div>
<div class="depth-1">a</div>
<div class="depth-2">b</div>
<div class="depth-3">c</div>
<div class="depth-4">d</div>

或者,使用纯 Javascript:

document.querySelectorAll('[class^=depth-]').forEach(function(el) {
  el.style.paddingLeft = (el.className.match(/(?:^|\s)depth-(\d+)(?:$|\s)/)[1] * 15) + "px";
})
<div class="depth-0">0</div>
<div class="depth-1">a</div>
<div class="depth-2">b</div>
<div class="depth-3">c</div>
<div class="depth-4">d</div>


推荐阅读