开发者

Multiple image elements all fading when hovered in Jquery.

开发者 https://www.devze.com 2023-04-04 18:22 出处:网络
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 wo

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消