根据第 n 个术语计数设置 CSS 样式



我有一个简短的 css nth-of-type()块,我想根据对象的 n 计数来设置对象的样式。我浏览了谷歌,但没有找到答案。这是我的代码:

a:nth-of-type(n + 3){
    top: 950px;
}

是否可以根据 n 计数更改top:位,使其看起来像:

a:nth-of-type(n + 3){
    top: 950px * n;
}

谢谢

简而言之,没有。

不幸的是,CSS 不是这样工作的。 不管它看起来像什么,n不会成为您可以在该样式块中使用的变量。 它用于指示您正在使用表单(an + b)来指定周期大小a和起始计数器b。 例如,a:nth-of-type(2n + 3)会选择从第三个开始的所有其他锚元素。

要做类似你所描述的事情,你需要使用 javascript 或 CSS 预编译器,如 LESS 或 SASS。

奖励:如果你很好奇,你可以在jQuery中做这样的事情来实现你试图用纯CSS做的事情:

$('a').each( function( n, element ) {
    if ( n > 2 ) $(element).css('top',(n*950)+'px');
});

或者,如果你想使用像 SASS 这样的预处理器(最好是用于样式的 JS 解决方案),你可以做这样的事情:

$max: 100 // or whatever maximum number of elements you need to account for
@for $i from 3 to $max
  a:nth-of-type(#{$i})
    top: #{$i*950}px

奖励2:这是David Thomas在评论中提出的一个相当优雅的纯JS解决方案:

Array.prototype.forEach.call(document.querySelectorAll('a'), function (aElem, index) {
    if (index > 2) {
        aElem.style.top = (index * 90) + 'px';
    }
});

http://jsfiddle.net/davidThomas/23nfskwb/(请注意,虽然使用较小的乘数 90 代替950,但这只是一个简单的演示,使用 950 是完全可以接受的)

不,这目前在 CSS 中是不可能的。

实现这样的事情的最佳方法是使用像SASS或LESS这样的预处理器,而不是使用JavaScript(或像jQuery这样的库)。这是因为样式应该尽可能不需要JavaScript,因为它会在每次加载页面后计算它,而不是像预处理器那样在服务器端进行。

在这里,我正在使用SCSS,一种更像CSS的SASS变体,来做你想做的事情(未经测试)。

$n:30; /* The max number of objects (really the max -3 number in your case) */
@for $i from 1 to $n {
  a:nth-of-type(#{$i} + 3) {
    top: 950px * #{$i};
  }
}

最新更新