简体   繁体   中英

How to find the first “visible” <li> inside a <ul> using jQuery?

I can't do $('ul li:first') or $('ul li:eq(0)') because they select the first item which is not necessarily the first visible item.

I'm using the jCarousel Lite plugin:

It works by moving the ul left by giving it negative margin every time next is clicked and moving it right when prev is clicked.

I want to give the first visible list item a red border color. The plugin doesn't add anything to the markup for the first visible item in the list so how can I target it?

PS $('ul li:visible').is(':first') won't work either because the plugin doesn't actually give the non visible lis any display none property.

Something a little fiddly. This works out the left offset applied to the jCarousel, divides it by the width of the li items inside to work out how many li s are left of this one, and then converts that into an :eq() inside.

var firstVisibleListItem = 0 - (parseInt($('.jCarouselLite ul').css('left')) / parseInt($('.jCarouselLite ul li').css('width'))) + 1
$('.jCarouselLite ul li').filter(':eq(' + firstVisibleListItem + ')').hide();

From: http://www.gmarwaha.com/jquery/jcarousellite/#doc you can use the afterEnd callback function:

afterEnd - Callback function that should be invoked after the animation ends. The elements representing the items that are visible after the animation ends are passed in as argument.

$(".carousel").jCarouselLite({
    btnNext: ".next",
    btnPrev: ".prev",
    afterEnd: function(a) {
       $(a[0]).addClass("redBorder");
   }
});

To select the first <li> , you'd do:

$('ul li').filter(":first");   // best performance, as indicated in the API documentation

Would you be able to figure out the first visible item (assuming you know how many items are visible at the same time) when the page is initially loaded? If yes, then you might be able to keep track by monitoring the prev / next button is clicked (eg when next is clicked, you'd increment your calculated position).

试试这个:) $('ul li:first-child')我经常使用它。

I give the first item a red border color from CSS.

.jCarouselLite ul li:first-child{
    border: 1px solid red;
}

尝试这个:

$('ul li').first(); // ta da?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM