簡體   English   中英

兩個部分的 HTML 不同樣式

[英]HTML different Styles for two sections

我想知道天氣有一種方法可以將兩種不同的樣式添加到 HTML 中的兩個代碼塊中。 例如,我有兩個部分

<section>
    <header class="major">
        <h2>Section 1</h2>
    </header>
</section>

<section>
    <header class="major">
        <h2>Section 2</h2>
    </header>
</section>

我想為以上兩個部分應用兩種不同的樣式。

請讓我知道是否有辦法做到這一點。

我會為您的每個部分添加一個類或 ID - 這正是它們的用途。

 /* Our base styles*/ section { border: dashed 1px black; padding: 1em; margin: 1em; font-weight: bold; color: #900; } /*Can over ride styles with classes*/ section.type-a { background-color: #fee; border: solid 4px red; } section.type-b { background-color: #efe; color: #060; }
 <section class="type-a"> <header class="major"> <h2>Section 1</h2> </header> </section> <section class="type-b"> <header class="major"> <h2>Section 2</h2> </header> </section>

我希望我現在得到了你的問題。 所以,你可以做什么,你可以將你的表格模板添加到另一個 div 中,並給它一個 class 。 現在,您可以定義一個樣式為您的section和另一section是在類中second-template 這樣,您可以為相同的樣式制作不同的樣式。

現在對於腳本,我已經編寫了一段示例代碼。 您可以相應地更改相同的內容。

$('.second-template').find('section').css("color", "green");

像這樣嘗試:

 $('.second-template').find('section').css("color", "green");
 section { background: red; } .second-template > section { background: blue; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section> <header class="major"> <h2>Section 1</h2> </header> </section> <div class="second-template"> /*Include your secoond template here */ <section> <header class="major"> <h2>Section 1</h2> </header> </section> </div>

CSS(除了幾乎沒有瀏覽器支持的作用域包含的CSS)和 JS 應用在文檔級別。

要將它們限制在文檔的特定區域,您必須將 CSS 和 JS 設計為以這種方式工作。 通常,您將使用以ID 選擇器(在將id屬性添加到您正在使用的每個組中的最外層元素后)和后代組合器(在 CSS 規則集的選擇器中或分別在querySelectorquerySelectorAll的參數中)。

您可以使用nth-of-type()選擇器:

section:nth-of-type(index){
   //Your rules
}

例子:

 section:nth-of-type(1){ color: green; } section:nth-of-type(2){ color: red; }
 <section> <header class="major"> <h2>Section 1</h2> </header> </section> <section> <header class="major"> <h2>Section 2</h2> </header> </section>

使用 CSS3 :nth-child() 選擇器,如下所示

section:nth-child(1) {
    //apply your changes to the first section
}

section:nth-child(2) {
    //apply your changes to the second section
}

如果需要到達不同的類,則需要按如下所示遍歷元素。 但關鍵是使用 nth-child 選擇器引用第一個元素,我認為不需要打擾腳本,下面的代碼適用於我並將不同的樣式應用於不同的元素。

<style type="text/css">
    section:nth-child(1) .major{
            background:red;
            height:100px;
            color:#fff;
    }

    section:nth-child(2) .major{
            background:blue;
            height:100px;
            color:lightcyan;
    }
</style>

<section>
    <header class="major">
        <h2>Section 1</h2>
    </header>
</section>


<section>
    <header class="major">
        <h2>Section 2</h2>
    </header>
</section>

暫無
暫無

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

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