I'm writing a simple jQuery plugin that displays images with a specific class in the center of the screen (when clicked, full-sized) with a gray overlay around the image. When we click on the overlay it disappears. Now I use this piece of code:
$("#overlay").click(function(){
$(this).animate({
opacity: "0"
}, 500, function(){
$(this).css({
display: "none"
});
});
$("#imgcontainer").animate({
opacity: "0"
}, 500, function(){
$(this).css({
display: "none"
});
});
});
imgcontainer holds our image. I was trying to use this easier code, but it doesn't work:
$("#overlay").click(function(){
$(this).add("#imgcontainer").animate({
opacity: "0"
}, 500, function(){
$(this).css({
display: "none"
});
});
});
Why it doesn't work?
UPDATE:
Correct code:$("#overlay").click(function(){
开发者_StackOverflow中文版 $("#imgcontainer").add(this).fadeOut();
});
Thanks a lot for replies. This behavior (bug?) is very surprising indeed.
If you're using v1.4.x, because of issue #7853 I just raised in their bug tracker earlier today (what timing!). You can fix it by changing this:
$(this).add("#imgcontainer").animate(...
to
$(this).add($("#imgcontainer")).animate(...
Update: Here's a better (more efficient) way, as Nick pointed out below:
$("#imgcontainer").add(this).animate(...
(See also his note about fadeOut
.)
In jQuery 1.3.2 and earlier, it would have worked as you expected. I don't know whether the 1.4.x thing is a bug or an intentional incompatible change.
Question though: Why not just fade out the container? If it contains the image, that should fade the image too, shouldn't it? As in this example? (I don't do a lot of animation, so apologies if I've missed something subtle.) Never mind, you never said #overlay was the image, that was an invalid assumption on my part.
精彩评论