CSS3 获取最后一个元素
- 作者: 占戈灬礻申
- 来源: 51数据库
- 2022-10-20
问题描述
如何从以下代码中获取最后一个元素 (hr):
<span class="hr"></span></div><span class="hr"></span></div><span class="hr"></span><!-- 我需要这个--></div></div>.hr:last-child 不适用于此.
当然,DOM 结构可能更复杂.我只需要获取最后需要的元素.
解决方案你的问题不太清楚;有几种方法可以从您的示例中获取最后一个 .hr 元素,但您说DOM 结构可能更复杂".为了回答您的问题,您需要提及您可能拥有的 DOM 结构;在某些情况下可能会,在某些情况下则不会.
这是从最后一个 div 中获取 .hr 的一种方法:
div div:last-of-type .hr这是从外部 div 的最后一个子元素中获取 .hr 的另一种方法:
div :last-child .hr如果你需要从文档中取出最后一个 .hr 元素,不管它在里面是什么,那么你不能在 CSS 中做到这一点.在 CSS 中,您只能选择层次结构的一个特定级别的第一个、最后一个或第 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 .hrHere's another way to get the .hr out of the last child of the outer div:
div :last-child .hrIf 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.
推荐阅读热点文章
检查拆分键盘0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView0
Activity 启动时显示软键盘0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?0
禁用 iPhone 中键盘的方向0
Android 2.3 模拟器上的印地语键盘问题0
keyDown 没有被调用0
