正如其他人所说,这在纯 CSS 中是不可能的。但是使用 js 是很有可能的,也相当容易。
为方便起见,我在 jQuery 中实现了这一点,但您可以使用纯 JS 来实现。
http://jsfiddle.net/sg3s/Suf3p/
我基本上制作了一个小型 jQuery 插件,它使用主颜色为您应用它的选择器着色,并使用子选择让匹配的子选择用次要颜色着色,依此类推,直到没有匹配子选择的子选择留下。
jQuery(function($) {
$.fn.alternateNestedBgColor = function(subselect, colors) {
// While not a great optimization, length of the colors array always stays the same
var l = colors.length;
// Itterate over all element in possible array
// jQuery best practice to handle initializing multiple elements at once
return this.each(function() {
var $sub = $(this), i = 0;
// Executes code, at least once
do {
// Set bg color for current $sub element
$sub.css('backgroundColor', colors[i++ % l]);
// Set $sub to direct children matching given selector
$sub = $sub.children(subselect);
// Will repeat the do section if the condition returns true
} while ($sub.length > 0);
});
};
// target first div in the body
// first argument = child selector
// second argument = array list of colors
$('body>div').alternateNestedBgColor('div', ['red', 'green', 'blue', 'purple', 'grey']);
});
更新根据要求,更新详细说明如何使用apply
和modulo
使用。
自从我最近发布此消息以来,已经快 2 年了。在工作时,我当时提出的解决方案有点冗长和混乱,例如,我从来不需要apply
. 我对范围更熟悉了,所以我修改了这个函数,让它变得更简单。
唯一apply
有用的情况是当您需要将值传递给this
函数范围内的变量时。除非使用类,否则在很多情况下您都不需要apply
or call
。如果您想阅读它,我想向您推荐这个答案,它在 classes 的上下文中解释它。MDN 链接也是一个很好的资源(对于这个和其他 javascript 结构/概念)。
至于modulo
,这是基本的数学,这个问题很好地解释了操作。简而言之,它会在将一个数字除以另一个数字后为您提供完整的整数余数。所以33 % 8 = 1
你可以像33-parseInt(33/8)*8
在 js 中那样写,虽然那会非常低效。运算的结果将始终为 0(当数字完全相除时)到第二个参数减去 1(在我的示例中为 7)。
0 % 3 = 0 // technically doesn't exist (as you can't divide 0 with anything) but 0 for practicality in all programming languages afaik(?)
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0 etc...
这是对您的 CPU 而言本质上很简单的操作之一,事实上,如果没有它能够做到这一点,我们就没有计算机。
在 javascript 修订版中,我将给定数组中的颜色选择编写为colors[i++ % l]
.
在写作中,这将给我剩余的i / l
整数并使用该整数作为数组的索引,该colors
数组返回一种颜色以供使用。
仅在返回用于模数的值后才会加 1,如果我写了,这种行为将被逆转,++
但这对我们的目的不起作用。i
++i
供参考的是 MDN 关于 do...while 的文章。
我希望能澄清一些事情!:)