<!DOCTYPE html>
<html>
<head>
<style>
.zebra:nth-child(odd) {
background: red;
}
</style>
</head>
<body>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<div>
<p class="zebra">Paragraph Inside</p>
<p class="zebra">Paragraph Inside</p>
</div>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<div>
<p class="zebra">Paragraph Inside</p>
<p class="zebra">Paragraph Inside</p>
</div>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>
</body>
</html>
上面有一系列段落zebra
类,但nth-child在容器内包装时重置。是否有可能即使在容器内也不会重置?
实际结果:
预期结果
w3schools链接:https://www.w3schools.com/code/tryit.asp?filename=FPLP7CUMGSPD
答案 0 :(得分:1)
不幸的是,仅使用:nth-child
伪类就无法做到这一点。
但是,您可以使用JQuery在页面上获取类的所有奇怪实例,并为它们添加一个类。使用此类,您可以根据需要设置样式。
一个例子:
$('.zebra:odd').addClass('highlight');
.highlight {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<div>
<p class="zebra">Paragraph Inside</p>
<p class="zebra">Paragraph Inside</p>
</div>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<div>
<p class="zebra">Paragraph Inside</p>
<p class="zebra">Paragraph Inside</p>
</div>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p class="zebra">Paragraph</p>
<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>
</body>
</html>
我希望这会有所帮助。