简体   繁体   中英

jQuery fade elements from one class to another, on hover

can this be done?

for eg.

.class1{
  background-image:(whatever.jpg)
  color: #fff;
}

.class2{
  background-image:(whatever2.jpg)
  color: #999;
}

can I fade all elements that have class1 to class2 when the mouse is over the element, and back to class1 when mouse is out?

If you don't want to use a plugin, you can do the following:

$(".class1").hover(
function () {
    $(this).fadeOut(function () {
        $(this).removeClass("class1").addClass("class2").fadeIn('fast');
    });
},
function () {
    $(this).fadeOut(function () {
        $(this).removeClass("class2").addClass("class1").fadeIn('fast');
    });
});

Have a look at jQuery UI's extension to addClass . It allows a duration parameter to give the possibility of animation.

Here, I think you want to do something like this:

$('.class1').hover(function(){
    $(this).addClass('class2', 800);
}, function(){
    $(this).removeClass('class2', 800);
});

Obviously you'll need to install jQuery UI for this.

I think this plugin is what you are looking for. It allows you to animate between classes. For example:

$('.class1').animateToClass('.class2', 1000);

如果你给两个相同的绝对位置,使用fadeIn()和fadeOut()将产生这种效果(附加到onmouseover和onmouseout)。

This is my implementation:

      $(this).fadeOut("fast"); or $(this).hide();
      $(this).removeClass('css1').addClass('css2');
 $(this).fadeIn("slow");

By providing Jquery hover() with the handlerIn and handlerOut functions as documented here you can easily handle the mouse in and mouse out events. Next, take a look at Jquery UI switchClass() to easily switch between two classes in a clean way. Lastly, adding fadeIn() makes all of this a clean transition.

$("div.class1").hover(
 function(){$("div").switchClass("class1", "class2").fadeIn(800);},
 function(){$("div").switchClass("class2", "class1").fadeIn(800);}
);

Working CodePen

i think this might be help full to you....

$('.class1').mouseover(function() {
    $(this).toggleClass('class2');
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM