jQuery-在悬停时添加类 [英] Jquery - add class on hover

查看:55
本文介绍了jQuery-在悬停时添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在鼠标继续按下li jquery时将一个类添加到元素:

I want when mouse goes on li jquery add a class to the element:

<ul class="menu">
  <li>Menu Item</li>
  <li>Menu Item</li>
  <li>Menu Item</li>
  <li>Menu Item</li>
</ul>

<script type="text/javascript">
var myMenu = $('.menu').children('li');

myMenu.on({
  mouseenter: function() { $( this ).addClass( "is_hovered" ); },
  mouseleave: function() { $( this ).removeClass( "is_hovered" ); }
});
</script>

但是我只想将鼠标移到另一个li上,而不是将保持放在元素上,则删除该类.

But I want to remove class only if mouse goes on another li, if not keep class on element.

这可能吗?

推荐答案

在这种情况下,请勿使用mouseleave处理程序,在mouseenter上,将悬停的类从其他元素中删除

Don't use the mouseleave handler in that case, on mouseenter remove the hovered class from other elements

var myMenu = $('.menu li');

myMenu.mouseenter(function () {
    myMenu.filter('.is_hovered').removeClass("is_hovered");
    $(this).addClass("is_hovered");
});

演示:小提琴

这篇关于jQuery-在悬停时添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆