在jQuery中使用nth-of-type选择前十个元素

Pix*_*omo 3 css jquery lazy-loading image jquery-selectors

我正在尝试将我的页面上的前十个图像作为目标 .lazy

我正在使用unveil来延迟加载图像,它等待滚动来加载图像,但是你可以触发所有图像加载这行:

$("img").trigger("unveil");

我想触发前10个图像总是直接显示,所以我试过这个:

$("#portfolio .portfolio-item img.lazy:nth-of-type(-n+10)").trigger("unveil");
Run Code Online (Sandbox Code Playgroud)

在CSS中:nth-of-type(-n+10)选择前十个匹配元素,但是当我使用这个jQuery在我的控制台上尝试这个时

$("img.lazy:nth-of-type(-n+10)")
Run Code Online (Sandbox Code Playgroud)

..it返回每个img的类 .lazy

我究竟做错了什么?有没有办法选择前十个而不是使用jQuery .eq

给你一些我的标记的想法:

<div class="portfolio">
     <div class="portfolio-item">
          <img class="lazy" src="item-1.jpg">
     </div>
     <div class="portfolio-item">
          <img class="lazy" src="item-2.jpg">
     </div>
     <div class="portfolio-item">
          <img class="lazy" src="item-3.jpg">
     </div>
     <div class="portfolio-item">
          <img class="lazy" src="item-4.jpg">
     </div>
     etc... (there 20 items in total)
</div>
Run Code Online (Sandbox Code Playgroud)

问题是每个img是否嵌套在一个单独的父级中?

Tus*_*har 6

您可以使用lt选择器来选择第一个n元素.

选择index匹配集中小于索引的所有元素.

$("#portfolio .portfolio-item img.lazy:lt(10)").trigger("unveil");
Run Code Online (Sandbox Code Playgroud)

演示