css - 如何根据 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”是任意数字。
解决方案
我们可以使用周围的方法来实现您正在寻找的东西,如下所示:
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>
推荐阅读
- python - Pyamg 不起作用(没有名为“pyamg.amg_core.evolution_strength”的模块)
- vaadin - 如何定义 CRUD 网格中的列?
- javascript - 使用 Next.js 的 scss 的类名约定
- javascript - Highcharts 标志在某些情况下不可见
- tensorflow - tf.nn.leaky_relu 和 tf.keras.layers.LeakyReLU 的区别?
- javascript - 在移动设备上第一次和第二次单击网页按钮时无法发送 GET 请求
- html - 单击颜色更改时的侧导航栏
- sql - 第二次存款次数
- c# - DataGridView 索引超出范围
- python - 谷歌不断关闭,无法弄清楚为什么,