开发者

JQuery Fade In Attr Change

开发者 https://www.devze.com 2023-01-25 03:48 出处:网络
I was wondering if it was possible to add a fadeIn effect when an attr is changed for example I have this code working, when 开发者_StackOverflowthe user clicks on img2 imgmain\'s src is changed to im

I was wondering if it was possible to add a fadeIn effect when an attr is changed for example I have this code working, when 开发者_StackOverflowthe user clicks on img2 imgmain's src is changed to img2's like this:

$('#img1').click(function() {
  $("#imgmain").attr("src","img1.jpg");
  });

  $('#img2').click(function() {
  $("#imgmain").attr("src","img2.jpg"); }

  );

Thank you!


You can change it on the fadeOut() callback, like this:

$('#img1').click(function() {
  $("#imgmain").fadeOut(function() {
    $(this).attr("src","img1.jpg").fadeIn();
  });
});


$('#img1').click(function() {
  $("#imgmain").fadeOut(function(){
  $(this).attr("src","img1.jpg");
  $(this).fadeIn();
  });
});


or...!

$('#MRMBIG').fadeOut('slow').attr('src',imgsrcclickshode).fadeIn('slow'); 


If you use the this keyword along with src, you don't have to iterate the image's source. For example

$('#img1').click(function() {
  var thisImage = this.src;
  $("#imgmain").fadeOut(function() {
    $(this).attr("src",thisImage).fadeIn();
  });
});

Better yet, you should give these images a classname also, this way it applies to them all. The above code will only work for the first image, while the code below, assuming they all have a class of thumb, will let you specify all of them

$('.thumb').click(function() {
  var thisImage = this.src;
  $("#imgmain").fadeOut(function() {
    $(this).attr("src",thisImage).fadeIn();
  });
});


You have redundancy in your code. Better:

$('#img1, #img2').click(function() {
  var src = $(this).attr("src");
  $("#imgmain").fadeOut(function() {
    $(this).attr("src", src).fadeIn();
  });
});

Usually, when you have multiple items, you use the class selector instead of listing the IDs of the items:

$(".images").click( ...

0

精彩评论

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

关注公众号