【问题标题】:jquery remove hover remove class name [duplicate]jquery删除悬停删除类名[重复]
【发布时间】:2013-08-16 19:09:36
【问题描述】:

我有这个 jQuery 代码,它在悬停时将类名 <li class="cat"> 替换为 <li class="cat show">。我悬停后它保持不变。 removeClass 代码有什么问题?

JS

jQuery(".cat").hover(function({
    jQuery(this).addClass('show').siblings().removeClass('show');
});

HTML

<ul> 
    <li class="cat"><a>Motors</a>    
        <ul> 
            <li>Top categories</li> 
            <li> <a href="" aria-haspopup="false">Cars</a></li>
            <li> <a href="" aria-haspopup="false">Motorcycles</a></li> 
            <li> <a href="" aria-haspopup="false">Parts</a></li> 
        </ul> 
    </li>
</ul>

【问题讨论】:

标签: jquery class hover


【解决方案1】:

jQuery中的hover事件需要2个回调函数:一个是指针移到item上,一个是离开:

在你的情况下:

jQuery(".cat").hover(
   function() {
      jQuery(this).addClass('show');
   },
   function() {
      jQuery(this).removeClass('show');
   }
);

见Hover

【讨论】:

  • 感谢亲爱的,它完美运行,哇 :)
【解决方案2】:

Hover 有两个功能:hover IN 和 hover OUT。

jQuery(".cat").hover(
  function() { 
    jQuery(this).addClass('show'); 
  },
  function() { 
    jQuery(this).removeClass('show'); 
  }
);

来源:jQuery api

【讨论】:

  • 该死!打败我。西部最快的枪。
  • 每件事都有第一次——我第一次跳了。
【解决方案3】:

jQuery 悬停函数有两个函数。首先是 mouseover 功能,其次是 mouseout 功能。要定义mouseout函数,只需在第一个函数后面加一个逗号,然后写第二个即可。

<script type="text/javascript">
jQuery(".cat").hover(
  function() {
     jQuery(this).addClass('show').siblings().removeClass('show');
  },
  function() {
     //mouseout stuff
  }
);
</script>`

【讨论】:

    【解决方案4】:

    .hover 通常为 mouseenter 和 mouseleave 事件提供 2 个 args 函数。

    但是.hover 也支持 1 个函数 arg,它基本上在 mouseenter 和 mouseleave 上执行相同的处理程序。

    尝试如下,

    <script type="text/javascript">
      jQuery(".cat").hover(function()  { //mouse enter 
         jQuery(this).addClass('show'); 
      }, 
      function () { //mouse leave 
          jQuery(this).removeClass('show');
      });
    </script>
    

    【讨论】:

      【解决方案5】:

      您还需要附加“mouseout 事件”

      $(function(){
      $("selector").hover(function(){
      //add class here
      }, function(){
          //remove class here
      });
      

      });

      基本上它需要两个参数 使用悬停事件就像添加 mouseenter 和 mouseout 事件

      你也可以这样做

      $(selector).mouseenter(function () {  add my class here});
      

      然后附加鼠标悬停

      $(selector).mouseout(function () { remove the class here});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 2013-12-18
        • 1970-01-01
        • 2010-12-30
        • 1970-01-01
        相关资源
        最近更新 更多