我刚刚了解到,我可以使用数据属性来选择元素,这是很棒的。然后,我想根据特定的计算,对这些元素进行不同的样式化。例如,我希望有4种样式,我希望使用元素的现有[data-pid]属性的模数来帮助确定样式。
例如,假设有一组div包含有四种字体颜色之一的文本(例如红色、橙色、黄色或绿色),而单个div的颜色取决于其模数4。我相信CSS (如果可能的话)会是这样的:
div[0=data-pid-modulus-by-4]{
color: red;
}
div[1=data-pid-modulus-by-4]{
color: orange;
}
div[2=data-pid-modulus-by-4]{
color: yellow;
}
div[3=data-pid-modulus-by-4]{
color: green;
}是否有可能仅用CSS来计算数据-pid/属性的模数,类似于我上面的说明,还是必须使用javascript来实现属性值的这个模数?如果不可能,有人能提出他们能想到的最小/最简单的js解决方案吗?
谢谢!
发布于 2017-01-12 20:45:43
下面是一个简单的JavaScript解决方案:
var pids = document.querySelectorAll('[data-pid]');
Array.prototype.forEach.call(pids, function(elem, index) {
elem.classList.add('pid-mod-' + (index % 4));
});.pid-mod-0 {
color: red;
}
.pid-mod-1 {
color: orange;
}
.pid-mod-2 {
color: yellow;
}
.pid-mod-3 {
color: green;
}<div data-pid="0">0</div>
<div data-pid="1">1</div>
<div data-pid="2">2</div>
<div data-pid="3">3</div>
<div data-pid="4">4</div>
<div data-pid="5">5</div>
<div data-pid="6">6</div>
<div data-pid="7">7</div>
如果所有元素都是彼此的兄弟,那么可以使用:nth-of-type()或:nth-child()。
div[data-pid]:nth-of-type(4n+1){
color: red;
}
div[data-pid]:nth-of-type(4n+2){
color: orange;
}
div[data-pid]:nth-of-type(4n+3){
color: yellow;
}
div[data-pid]:nth-of-type(4n+4){
color: green;
}<div class="only-pids-in-here">
<div data-pid="0">0</div>
<div data-pid="1">1</div>
<div data-pid="2">2</div>
<div data-pid="3">3</div>
<div data-pid="4">4</div>
<div data-pid="5">5</div>
<div data-pid="6">6</div>
<div data-pid="7">7</div>
</div>
发布于 2017-01-12 16:44:35
您不能直接在CSS中计算值,也不能使用SASS/LESS来计算。
为了做到这一点,您必须使用Javascript。
这是完全有意义的,因为在CSS中计算html的部分,即使是可行的,也是可怕的做法。
发布于 2017-01-12 16:50:15
不能使用选择器中的属性选择器的值执行算术计算。属性值总是字符串,最多只支持子字符串匹配。
https://stackoverflow.com/questions/41618475
复制相似问题