【问题标题】:How to add a css class in a loop to the 2nd, 5th, 8th and 11th item如何在循环中将css类添加到第2、5、8和11项
【发布时间】:2017-03-15 23:03:29
【问题描述】:

我在 SilverStripe 模板中有一个循环。在循环的第 2、5、8、11 等项上,我需要添加一个 css 类 .service-border

如何使用 SilverStripe 模板语言实现这一点?

<div class="container">
    <% loop $ServiceBlockItems %>
        <% if $First %>
            <div class="row equal-height-columns">
        <% end_if %>

            <%-- Every 2, 5, 8, 11th iteration I need to add a .service-border class --%>
            <div class="col-md-4 service-inner equal-height-column">
                <i class="icon-custom icon-md rounded-x icon-bg-u $IconName"></i>
                <span>$ServiceHeader</span>
                <p>$Summary</p>
            </div>

        <% if $MultipleOf(3) && not $Last %>
        </div><!-- /end row -->
        <div class="row equal-height-columns">
        <% end_if %>
    <% end_loop %>
        </div><!-- /end row -->
</div><!-- /end container -->

【问题讨论】:

    标签: silverstripe


    【解决方案1】:

    然后在我们的模板中添加一个类,我们可以使用 css :nth-child 选择器来定位我们想要的任何元素。

    .container .service-inner:nth-child(2),
    .container .service-inner:nth-child(5),
    .container .service-inner:nth-child(8),
    .container .service-inner:nth-child(11) {
        background-color: red;
    }
    

    或者,如果我们想从元素 2 开始每隔三个元素定位,我们可以使用以下 css 选择器:

    .container .service-inner:nth-child(3n - 1) {
        background-color: green;
    }
    

    nth-child是一个css3选择器,现在有很好的browser support

    【讨论】:

    • 完美,第二个例子是我应该做的,已经测试过并且可以完美运行。因为我希望它是动态的而不是设置的,所以从元素 2 开始,从那时起每隔三个元素设置样式。谢谢@3dgoo! :)
    【解决方案2】:

    虽然我也更喜欢使用 CSS,但以下是使用 SilverStripe 模板的方法:

    <% loop $Items %>
        <% if $MultipleOf(3, 2) %>
            <div class="item service-border">
        <% else %>
            <div class="item">
        <% end_if %>
            $Value
        </div>
    <% end_loop %>
    

    注意$MultipleOf 的第二个参数。您可以使用它来设置偏移量。

    【讨论】:

    • 完美,很高兴知道如何在 Silverstripe 模板中做到这一点。谢谢! :)
    • 这可能是个人喜好,但我更倾向于这样做:
    猜你喜欢
    • 2017-03-24
    • 2021-01-29
    • 2014-03-09
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多