How to remove/toggle hover class on an element (th

2019-02-23 13:06发布

问题:

If you click and don't move your mouse you'll see the button's color remaining as red! What I want accomplish is after you click and don't move the mouse it still removes/toggles .hover class.

Example on jsFiddle

$(function() {
  var $Btn = $('.button');

  $Btn.hover(function() {
    $(this).toggleClass("hover");
  });


  $Btn.on("click", function() {
    $(this).toggleClass('active')
    $('.move').toggleClass('angle');
  });
});
.move {
  border: 1px solid #000000;
  padding: 10px;
  transition: transform .2s ease;
  /* 
        have noticed issue is in "transition" 
    */
}
.button.hover {
  color: red;
}
.angle {
  transform: translate(100px, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="move">
  <button class="button">on click still red?</button>
</div>

回答1:

The element is retaining the hover class even after the button is clicked (and container is translated) because the browser doesn't seem to be calling the hover-out (or mouseout) till the mouse is actually moved.

One way to fix this would be to remove the hover class within the click event handler of the button. But for this to work the hover event handler's code needs to be changed to specifically add class on mouseover (hover-in) and remove it on mouseout (hover-out). This is needed because as per current code even though hover class is removed within the click event handler, it gets toggled back on the moment the mouse is moved again (because at that point in time, the handler for hover doesn't see the class on the element).

The change to the code can actually be done in two ways - either by using separate mouseover and mouseout functions (like in my original fiddle) or by passing two separate functions to hover handler. When two functions are passed, the first one gets called on hover-in and the second on hover-out.

$(function () {
  var $Btn = $('.button');

  $Btn.hover(function () {
    $(this).addClass("hover");
  },function () {
    $(this).removeClass("hover");
  }); /* first function is executed on mouseover, second on mouseout */

  $Btn.on("click", function () {
    $(this).removeClass('hover'); // remove the hover class when button is clicked
    $('.move').toggleClass('angle');
  });
});
.move {
  border:1px solid #000000;
  padding: 10px;
  transition: transform .2s ease;
  /* 
  have noticed issue is in "transition" 
  */
}
.button.hover {
  color: red;
}
.angle {
  transform: translate(100px, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="move">
    <button class="button">on click still red?</button>
</div>