如何为Bootstrap网格系统交替设置行颜色

huangapple go评论49阅读模式
英文:

How to alternate a row color for a Bootstrap grid system

问题

我有一个循环在我的模型中,我只想使每个交替的Div行变成不同的颜色。有没有办法我可以检查我的变量i模2 == 0,然后设置背景颜色,或者有更好的方法

@for (var i = 0; i < Model.Transactions.Count; i++)
{
<div class="row">
<div class="col">
<label asp-for="@Model.Transactions[i].TransactionId" />@Model.Transactions[i].TransactionId
</div>

英文:

I have a loop on my MODEL in the view and I simply want to make every alternate Div ROW a different color. Is there a way I can check if my variable i Modulus by 2 ==0 and then set the backcolor, or is there even a better way

                        @for (var i = 0; i &lt; Model.Transactions.Count; i++)
                        {
                            &lt;div class=&quot;row&quot;&gt;
                                &lt;div class=&quot;col&quot;&gt;
                                    &lt;label asp-for=&quot;@Model.Transactions[i].TransactionId&quot; /&gt;@Model.Transactions[i].TransactionId
                                &lt;/div&gt;

答案1

得分: 1

I don't have any code to translate in the provided text.

英文:

Your own answer uses the right modulus operator to check for an even/odd index value.

> I don't know if this the best way to do it but below is how I overcome my issue

Adding a class name instead enables more style flexibility. (The snippet below assumes you have a section called Styles in your _Layout.cshtml.)

@section Styles {
    &lt;style&gt;
        .odd-row {
            background-color: #f1f1f1;
        }

        .even-row {
            background-color: #e1e1e1;
        }
    &lt;/style&gt;
}

@for (int i = 0; i &lt; Model.Transactions.Count; i++)
{
    string altClassName = i % 2 == 0 ? &quot;even-row&quot; : &quot;odd-row&quot;;
    &lt;div class=&quot;row @altClassName&quot;&gt;
        &lt;div class=&quot;col&quot;&gt;
            &lt;label asp-for=&quot;@Model.Transactions[i].TransactionId&quot;&gt;@Model.Transactions[i].TransactionId&lt;/label&gt;
        &lt;/div&gt;
    &lt;/div&gt;
}

答案2

得分: 0

我不知道这是否是最佳方法,但以下是我克服问题的方式

<div class="row" style="@(i%2 == 0 ? &quot;background-color:aliceblue&quot; : &quot;background-color:white&quot;)">
英文:

I don't know if this the best way to do it but below is how I overcome my issue

&lt;div class=&quot;row&quot; style=&quot;@(i%2 == 0 ? &quot;background-color:aliceblue&quot; : &quot;background-color:white&quot;)&quot;&gt;

huangapple
  • 本文由 发表于 2023年4月4日 05:58:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定