12

我正在做一个小实验,尝试为嵌套的 div 替换背景颜色。

这就是我打算实现的(没有内联样式):

<div style="background: #fff;">
    <div style="background: #000;">
        <div style="background: #fff;">
            <div style="background: #000;">
                and so on...
            </div>
        </div>
    </div>
</div>

我觉得我一定错过了一些明显的东西!我试过div:nth-of-type(2n)了,但这似乎只适用于一个级别。

这是针对生成 div 的实验,因此解决方案需要是无止境的(不是像 div div div div = white 那样的东西)。我知道使用 JavaScript 很容易,只需寻找一个纯 CSS 解决方案

4

2 回答 2

6

正如 Lister 先生所指出的,nth-of-type 在一个级别(所选 div 的父级)上工作。

据我所知,在查看了W3C CSS3 选择器之后,似乎没有任何用于遍历嵌套的 css 选择器(> 选择器除外,它只查看父级的直接子级)。

我希望你被证明是错误的,因为这可能非常有用。

所以唯一的(css)解决方案就是你已经说过的那个:div > div > div {background: white; } 你不能在生成div的同时生成这个吗?

于 2012-04-07T15:10:41.497 回答
4

正如其他人所说,这在纯 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']);
});

更新根据要求,更新详细说明如何使用applymodulo使用。

自从我最近发布此消息以来,已经快 2 年了。在工作时,我当时提出的解决方案有点冗长和混乱,例如,我从来不需要apply. 我对范围更熟悉了,所以我修改了这个函数,让它变得更简单。

唯一apply有用的情况是当您需要将值传递给this函数范围内的变量时。除非使用类,否则在很多情况下您都不需要applyor 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 的文章

我希望能澄清一些事情!:)

于 2012-04-07T15:30:14.140 回答