問題描述
如何從以下代碼中獲取最后一個元素 (hr):
<span class="hr"></span></div><span class="hr"></span></div><span class="hr"></span><!-- 我需要這個--></div></div>.hr:last-child
不適用于此.
當(dāng)然,DOM 結(jié)構(gòu)可能更復(fù)雜.我只需要獲取最后需要的元素.
解決方案 你的問題不太清楚;有幾種方法可以從您的示例中獲取最后一個 .hr
元素,但您說DOM 結(jié)構(gòu)可能更復(fù)雜".為了回答您的問題,您需要提及您可能擁有的 DOM 結(jié)構(gòu);在某些情況下可能會,在某些情況下則不會.
這是從最后一個 div
中獲取 .hr
的一種方法:
div div:last-of-type .hr
這是從外部 div
的最后一個子元素中獲取 .hr
的另一種方法:
div :last-child .hr
如果你需要從文檔中取出最后一個 .hr
元素,不管它在里面是什么,那么你不能在 CSS 中做到這一點.在 CSS 中,您只能選擇層次結(jié)構(gòu)的一個特定級別的第一個、最后一個或第 n 個元素,無論嵌套在什么中,都不能選擇某種類型的最后一個元素.
How I can get the last element (hr) from the following code:
<div>
<div>
<span class="hr"></span>
</div>
<div>
<span class="hr"></span>
</div>
<div>
<span class="hr"></span> <!-- I need this -->
</div>
</div>
.hr:last-child
doesn't work for this.
Of course, DOM structure could be more complicated. I just need to fetch the last needed element.
解決方案 Your question isn't quite clear; there are several ways to get the last .hr
element from your example, but you say "DOM structure could be more complicated." In order to answer your question, you need to mention what possible DOM structures you could have; in some it might be possible, in some it will not be.
Here is one way to get the .hr
out of the last div
:
div div:last-of-type .hr
Here's another way to get the .hr
out of the last child of the outer div
:
div :last-child .hr
If you need to get the last .hr
element out of the document, regardless of what it's inside, then you can't do that in CSS. In CSS, you can only select the first, last, or nth element at one particular level of the hierarchy, you can't select the last element of some type regardless of what it's nested in.
這篇關(guān)于CSS3 獲取最后一個元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!
相關(guān)文檔推薦
CSS selector when :target empty(:target 為空時的 CSS 選擇器)
Does the CSS direct decendant (gt;) not have any value in selectivity?(CSS 直接后代 (gt;) 在選擇性方面沒有任何價值嗎?)
Using querySelectorAll(). Is the result returned by the method ordered?(使用 querySelectorAll().方法返回的結(jié)果是否有序?)
Safari bug :first-child doesn#39;t update display:block when items are removed with JS(Safari 錯誤:當(dāng)使用 JS 刪除項目時,first-child 不更新 display:block)
nth-Child CSS selectors(nth-子 CSS 選擇器)
Using same ID for multiple HTML tags?(對多個 HTML 標(biāo)簽使用相同的 ID?)