I am having trouble getting this jQuery to work. I am trying to toggle overlaid divs' visibility. There are five divs and one has the class of 'on' with page load while the rest have the class 'off'. However, when the code executes, the "on" div fades out but the div that should receive the class "on" does not appear. What is the problem?
.on{opacity:1;}
.off{opacity:0;)
$('li.tunes').click(
function() {
$('div.on').animate({"opacity":"0"}开发者_JAVA百科,800).removeClass('on').addClass('off', function() {
$('div.tunesdiv').removeClass('off').addClass('on')
})
});
Your syntax is pretty off, and you're missing a couple semi-colons. Try something more like:
$('li.tunes').click(function(){
$('div.on').animate({"opacity":"0"},800).removeClass('on').addClass('off', function(){
$('div.tunesdiv').removeClass('off').addClass('on');
});
});
Also, it's good if you'd provide the source as you have it.
You can use jQuery's fadeIn
( ref ) and fadeOut
( ref )to animate your opacity.
Handing that task to jQuery also helps you with supporting older IE versions that did not suppor the opacity
CSS attribute.
That second function parameter in addClass seems totally wrong to me, you need to use a handler in the animate function instead.
Here is the code I recommend (.fadeTo() animates the opacity and here is more readable)
try this:
also because fadeTo() will give your element explicit style you need to forget about stylesheets and let your script to rule-out on opacity:
$('li.off').fadeTo(1, 0);
$('li.on').fadeTo(1, 1);
$('li.tunes').click(function() {
$('div.on').fadeTo(800, 0, function() {
$(this).removeClass('on').addClass('off');
$('div.tunesdiv').fadeTo(1, 1).addClass("on").removeClass("off");
});
});
精彩评论