簡體   English   中英

KnockoutJS表包含交替行顏色的樣式

[英]KnockoutJS table incorporating style for alternating row colors

我在我的HTML中使用KnockoutJS將表行的可見性數據綁定到某些可觀察值,如我隨附的JavaScript中所定義。 我的表看起來像這樣:

<table class="myTable">
    <tr data-bind="if: thisRowVisible"> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: thatRowVisible"> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: anotherRowVisible"> <!-- Arbitrary data here --> </tr>
    <!-- More rows defined here -->
</table>

作為應用程序運行時,表中的行可以被隱藏或顯示,通過使用這些數據綁定if值。 為了給表格的行交替顏色(斑馬/條紋),我在CSS中定義了以下內容:

.myTable tr:nth-child(even) td {
   background-color: black;
}
.myTable tr:nth-child(odd) td {
   background-color: gray;
}

通常,這個CSS會正確地設置行的樣式。 偶數行將顯示為黑色,奇數行將顯示為灰色。 但是,當您拋出Knockout數據綁定時,我的問題就出現了。

例如,假設我的數據綁定導致索引#2行被隱藏。 即使該行被隱藏,該行的<tr>定義仍然存在於表中。 這會拋棄交替的行顏色。 由於索引#2仍然存在,但是被隱藏,它仍然包含在交替的行顏色中。 這意味着兩個灰色行將顯示在彼此之上。

是否有任何可以實現正確的交替表行顏色,同時仍然使用我的KnockoutJS模式? KO數據綁定是否有一些技巧可以完全從Markup中刪除隱藏的<tr> ,以便正確應用CSS樣式?

您可以使用虛擬元素<!-- ko 'if': thisRowVisible -->
工作示例: http//jsfiddle.net/zs4B2/1/

您可以將特定類僅分配給可見元素,並僅為該類應用斑馬紋樣式。 數據綁定如下所示:

<table class="myTable">
    <tr data-bind="if: thisRowVisible, attr: {'class': thisRowVisible ? 'rowVisible' : 'rowInvisible' "> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: thatRowVisible, attr: {'class': thatRowVisible ? 'rowVisible' : 'rowInvisible'"> <!-- Arbitrary data here --> </tr>
    <tr data-bind="if: thatIsNotVisible, attr: {'class': thatIsNotVisible ? 'rowVisible' : 'rowInvisible'"> <!-- Arbitrary data here --> </tr>
    <!-- More rows defined here -->
</table>

CSS

.myTable tr.rowVisible:nth-child(even) td {
   background-color: black;
}
.myTable tr.rowVisible:nth-child(odd) td {
   background-color: gray;
}

FIDDLE示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM