问题
I have an list of images with the following markup:
<a href="#" id="toggle-16561" onclick="toggleImages(16561); return false;">show images</a>
<div class='image-container-box clearfix' id='image-container-box-16561'>
<span class='image-box'>
<a href="/images/1.jpg"><img src="/images/1_thumb.jpg" /></a>
</span>
<span class='image-box'>
<a href="/images/2.jpg"><img src="/images/2_thumb.jpg" /></a>
</span>
etc ....
</div>
</div>
I could have a bunch of these on a web page (like 20 or more). I originally didn't want to show any of the thumbs and thus have all the .images-container-box set to hide. I'd like to have the first 3 images be shown and the remainder be hidden. It seems what I want to do is say on initial load hide all the .image-container-box.image-box that are > 3 in the img array of the element. How would I do this?
thx
回答1:
$(".image-container-box .image-box:gt(2)").hide();
or:
$(".image-container-box .image-box").slice(2).hide();
Demo.
回答2:
It's jQuery's slice method:
$(".images-container-box").slice(0,2).show();
$(".images-container-box").slice(3).hide();
Using slice
is more efficient than gt(n)
, lt(n)
or the other positional selectors because jQuery somewhy loops through the entire set when evaulating gt, lt, etc..
.
回答3:
First hide them using CSS (if you havent done that already):
.image-container-box{display:none}
Then show the first three using jQuery and the :lt() selector:
$('.image-container-box:lt(3)').show();
回答4:
CSS version:
.image-box {display:none;}
.image-box:first-child, .image-box:nth-child(2), .image-box:nth-child(3) {display: block;}
来源:https://stackoverflow.com/questions/9352160/jquery-showing-first-three-images-of-a-gallery-hiding-the-remainder