首页 > 解决方案 > Combining addClass with fadeIn on mouseenter

问题描述

So, I have written JavaScript code that uses the JQuery library to swap classes on hover.

$("#workBG").on({
mouseenter : function() {
  $("#workplay").addClass("workBG", 200);
  $("#workplay").removeClass("diagR", 200);
}
,
mouseleave : function() {
  $("#workplay").addClass("diagR", 200);
  $("#workplay").removeClass("workBG", 200);
 }
})

This code works but I would like to have the class fadeIn and fadeOut considering that it swaps background images but it does so harshly without the fadeIn and fadeOut. I have seen similar questions but they were all from five or six years ago and I would like to know if there is any better way to do this now.

From one of the older questions, I saw that they had answered with

.addClass("workBG", 200);

where the 200 is the time for the class to fadeIn. As far as I can tell, this does not work now or I am doing something wrong. I did check the JQuery documentation and there was nothing about this under the addClass API documentation.

In Addition:

HTML code:

<div id="workplay" class ="row text-center mt-5 diagR">
  <div class ="col-sm-6 align-self-center changework">
    <p id= "workBG" class ="display-1 font-weight-bold text-warning">WORK.</p>
  </div>
  <div class ="col-sm-6 align-self-center">
    <p id= "playBG" class ="display-1 font-weight-bold">PLAY.</p>
  </div>
</div>

This is the html code that is related to the JS and the backgrounds are applied through the classes.

标签: javascriptjquery

解决方案


just add transition property on your element don't use 2nd parameter with addClass / removeClass function

$("#workBG").on({
  mouseenter: function() {
    $("#workplay").addClass("workBG");
    $("#workplay").removeClass("diagR");
  },
  mouseleave: function() {
    $("#workplay").addClass("diagR");
    $("#workplay").removeClass("workBG");
  }
})
#workplay {
  transition: 2s;
}

.workBG {
  background: red;
}

.diagR {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="workBG">
  <div id="workplay">asdasdasd</div>
</div>


推荐阅读