如何删除/切换元素上的hover类(在单击时翻译)而不必再次移动鼠标?
如果您单击并且不移动鼠标,您将看到按钮的颜色保持为红色! 我想要完成的是在你点击并且不移动鼠标之后它仍然移除/切换.hover
类。
关于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); }
即使单击按钮(并且容器已翻译),该元素仍保留hover
类,因为浏览器似乎没有调用hover(或鼠标移出)直到鼠标实际移动。
解决此问题的一种方法是删除按钮的click
事件处理程序中的hover
类。 但为了实现这一点,需要将hover
事件处理程序的代码更改为在mouseover(hover-in)上专门添加类,并在mouseout(hover-out)上删除它。 这是必需的,因为根据当前代码,即使在click事件处理程序中删除了hover
类,它也会在鼠标再次移动时切换回来(因为在那个时间点, hover
的处理程序看不到类在元素上)。
对代码的更改实际上可以通过两种方式完成 – 通过使用单独的mouseover
和mouseout
函数(如在我的原始小提琴中)或通过将两个单独的函数传递给hover
处理程序。 传递两个函数时,第一个函数在hover-in上调用,第二个函数在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); }