Problem demo is here: http://www.studioimbrue.com
Currently, when the page loads, all the thumbnails are triggered to dim. I'm trying to make it so that each first thumb remains at full opacity (using :first
of course) until another thumb is clicked. I can get it to do it for the first one, but it won't iterate to each <ul>. I tried using the each()
function, but I couldn't get it to work. My JavaScript skills aren't that great so if you find a solution, just post the code and then explain (if you can).
Below is the current code I'm working with:
$(document).ready(function(){
var activeOpacity = 1.0,
inactiveOpacity = 0.6,
fadeTime = 100,
clickedClass = "selected",
thumbs = ".thumbscontainer ul li";
$(thumbs).fadeTo(1, inactiveOpacity);
$(thumbs).hover(
function(){
$(this).fadeTo(fadeTime, activeOpacity);
},
function(){
// Only fade out if the user hasn't clicked the thumb
if(!$(this).hasClass(clickedClass)) {
$(this).fadeTo(fadeTime, i开发者_开发问答nactiveOpacity);
}
});
$(thumbs).click(function() {
// Remove selected class from any elements other than this
var clicked, previous;
clicked = $(this);
if (!clicked.hasClass(clickedClass)) {
previous = $(thumbs+'.'+clickedClass);
previous.removeClass(clickedClass).fadeTo(fadeTime, inactiveOpacity);
clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
}
});
});
You need :nth-child()
or :first-child
:
$(".thumbscontainer li:nth-child(1)")
And actually, just change the line that reads $(thumbs).fadeTo(1, inactiveOpacity);
to this instead:
$(thumbs).not(':first-child').fadeTo(1, inactiveOpacity)
.end().filter(':first-child').addClass(clickedClass);
:first
returns a single item which is index 0
in the result set. :nth-child(1)
returns any item that is the first child of its parent, which is subsequently, the first li in each list.
Important: When using :nth-child
it is important to realize that the number passed to the selector is 1
based, not 0
based like most arrays or selectors. :nth-child(1)
is the first child, :nth-child(2)
is the second, and so forth.
Thanks Nick!
精彩评论