簡體   English   中英

將與一個元素的 ID 關聯的 CSS 應用到另一個元素

[英]Applying CSS associated with ID of one element to another element

我希望將與#originalTable 關聯的css 應用到#newTable。

大多數樣式將與類 .general 相關聯,但是,正是這種特定於 ID 的樣式讓我感到困惑。 #originalTable 將保留在 DOM 中,所以我不能只移動 ID。 我寧願不手動迭代每個元素來關聯樣式,因為大多數樣式通常由類 .general 應用。 我也不希望為#newTable 或應用於#newTable 的某些新類復制樣式表中的規則。

如何做到這一點? 謝謝

CSS

.general {//some CSS}
.general thead {//some CSS}
.general thead th {//some CSS}

#originalTable {//some CSS}
#originalTable thead {//some CSS}
#originalTable thead th  {//some CSS}

HTML

<table id="originalTable" class="general">
    <thead>
        <tr>
            <th>H1</th>
            <th>H2</th>
            <th>H3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>B1</th>
            <th>B2</th>
            <th>B3</th>
        </tr>
    </tbody>
</table>

<table id="newTable" class="general">
    <thead>
        <tr>
            <th>H1</th>
            <th>H2</th>
            <th>H3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>B1</th>
            <th>B2</th>
            <th>B3</th>
        </tr>
    </tbody>
</table>
#originalTable, #newTable {//some CSS}
#originalTable thead, #newTable thead {//some CSS}
#originalTable thead th, #newTable thead th  {//some CSS}

您應該將代碼更改為:

CSS:

.general {//some CSS}
.general thead {//some CSS}
.general thead th {//some CSS}

.originalTable {//some CSS}
.originalTable thead {//some CSS}
.originalTable thead th  {//some CSS}

HTML:

<table class="general">
    <thead>
        <tr>
            <th>H1</th>
            <th>H2</th>
            <th>H3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>B1</th>
            <th>B2</th>
            <th>B3</th>
        </tr>
    </tbody>
</table>

<table class="general originalTable">
    <thead>
        <tr>
            <th>H1</th>
            <th>H2</th>
            <th>H3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>B1</th>
            <th>B2</th>
            <th>B3</th>
        </tr>
    </tbody>
</table>

如果您想讓所有表都具有 CSS 屬性,請使用:

table {
    //some CSS code
}

如果您希望所有“通用”表都具有某些屬性,請使用:

.general { 
    //some CSS code
}

如果您希望某些“特殊”表具有附加屬性,請使用:

.special { 
    //some CSS code 
}

如果您只希望 1 個特定表具有屬性,請使用:

#newTable { 
    //some CSS code
}

如果您希望 2 個表具有屬性,請使用:

#newTable, #oldTable {
    //some CSS code
}

請注意,可以進一步指定最后一個。 例如#newTable head, #oldTable head

那么你可以有

<table id="newTable" class="general special">
    //some HTML code
</table>

暫無
暫無

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

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