假设这个 HTML:
<h1>heading</h1>
<p>foo</p>
<p>bar</p><!---this should be selected--->
<h1>heading</h1>
<p>foo</p>
<p>bar</p>
<p>foo</p>
<p>bar</p><!---this should be selected--->
而且只用 CSS 选择这个是不可能的吗?
我是这样尝试的:
h1 ~ p:last-child /*wouldn't work*/ /* it would select last-child of p*/
最佳答案
这对于 CSS 来说根本不可能,因为没有办法向后或向上选择元素(期待 CSS4……)。您将不得不使用其中之一:
<section>
<h1>heading</h1>
<p>foo</p>
<p>bar</p><!---this should be selected--->
</section>
(section p:last-child
) 或者:
<h1>heading</h1>
<p>foo</p>
<p class="last">bar</p><!---this should be selected--->
(p.last
) 或者用 JS:
var e = document.getElementsByTagName('h1');
for (var i = 0; i < e.length; i++) {
var f = e[i].nextSibling;
while (f && f.tagName == 'P') {
var n = f.nextSibling();
if (!n) {
f.classList.add('last');
} else {
f = n;
}
}
}
关于html - 如何获得每个标题的最后一个 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497096/