当标记更改时,选择第n个类型为(1)的第一个实例的CSS选择器失败

Moi*_*man -1 html css css-selectors

这让我很难过......

在这看到JSBIN

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<style>
    .slide-nav:nth-of-type(1) { color:red } /* this should select the number 1 */
</style>
</head>
<body>

  <div class="image">
    <span class="slide" data-order="4" rel="content-images/teta.jpg" ></span>
    <span class="slide" data-order="3" rel="content-images/champ.jpg" ></span>
    <span class="slide" data-order="2" rel="content-images/clouds.jpg" ></span>
    <img class="slide initial" data-order="1" src="content-images/air.jpg" />
    <span class="spinner"></span>

    <!--  
    delete this line to comment the two arrow links -->
    <a class="arrow next" href="javascript:void(0)">&rarr;</a>
    <a class="arrow prev" href="javascript:void(0)">&larr;</a>
    <!-- -->

    <a class="slide-nav on" href="javascript:void(0)" rel="1">1</a>
    <a class="slide-nav" href="javascript:void(0)" rel="2">2</a>
    <a class="slide-nav" href="javascript:void(0)" rel="3">3</a>
    <a class="slide-nav" href="javascript:void(0)" rel="4">4</a>
  </div>


</body>
</html>
Run Code Online (Sandbox Code Playgroud)

为什么.slide-nav:nth-of-type(1) { color:red }只删除数字上方的两个附加链接才能工作?

在jsbin中,删除两个箭头,或删除注释行以注释该块,您将看到.slide-nav:nth-of-type(1)选择器神奇地工作.

对于我的生活,似乎它应该只是工作.我在这里错过了什么?

hal*_*lex 5

CSS中没有按类过滤,因为它没有:nth-​​of-class()选择器.:nth-of-type过滤器必须在标签上.

解决方法是将滑动导航链接包含在跨度内并过滤aCSS中的所有内部.

<span class="numbers">
    <a class="slide-nav on" href="javascript:void(0)" rel="1">1</a>
    <a class="slide-nav" href="javascript:void(0)" rel="2">2</a>
    <a class="slide-nav" href="javascript:void(0)" rel="3">3</a>
    <a class="slide-nav" href="javascript:void(0)" rel="4">4</a>
</span>
Run Code Online (Sandbox Code Playgroud)

和CSS

span.numbers a:nth-of-type(1) { color:red; } /* this should select the number 1 */
Run Code Online (Sandbox Code Playgroud)

有关示例,请参阅http://jsfiddle.net/3J4K6/

  • @Moin Zaman,如果删除了箭头,那么内容为"1"的`a`元素将成为`div`中其类型的第一个子元素(即第一个`a`元素).但是当箭头在那里时,它们中的第一个(而不是你想要的元素)匹配选择器`:nth-​​of-type(1)`.由于它与`.slide-nav`不匹配,因此组合选择器`.slide-nav:nth-​​of-type(1)`与此处的任何元素都不匹配. (3认同)