问题
I'm having an issue with applying a fade to just one element on the page with the same ID.
Firstly I fade the image down to 60% and then on hover I would like it to just 100% the image. This part works but it applies the effect to every element on the page.
// Fading images
$(document).ready(function(){
$('.mainArticle img').fadeTo('slow', 0.6);
$('.mainArticle img, .articleContainer').hover(function(){
$(this).find('.mainArticle img, .articleContainer').stop(true,true).fadeTo("slow", 1.0);
},function(){
$(this).find('.mainArticle img, .articleContainer').stop(true,true).fadeTo("slow", 0.6);
});
});
Also I know this can be done if CSS but trying to be as compatible as possible.
Hope you guys can help,
Cheers,
Tom
回答1:
You are find()
ing the same elements again. $(this)
is the hovered element, so you can just use this for your hover handler:
$('.mainArticle img, .articleContainer').hover(function(){
$(this).stop(true,true).fadeTo("slow", 1.0);
},function(){
$(this).stop(true,true).fadeTo("slow", 0.6);
});
However, I think I understand what you are trying to do, and depending on your HTML (if you could post your HTML it would be a lot easier), you'll probably want to change it to something like this:
$(function(){
$('.mainArticle img').fadeTo('slow', 0.6);
$('.articleContainer').hover(function(){
$(this).find('.mainArticle img').stop(true,true).fadeTo("slow", 1.0);
},function(){
$(this).find('.mainArticle img').stop(true,true).fadeTo("slow", 0.6);
});
});
With only one image to fade: jsFiddle
With multiple images to fade: jsFiddle
回答2:
How about just using $(this) instead of $(this).find('.mainArticle img, .articleContainer')?
You're selecting every element that matches that selector, but since you're already hovering one, you could just use $(this) and perform the change there.
来源:https://stackoverflow.com/questions/7402897/multiple-image-elements-all-fading-when-hovered-in-jquery