简体   繁体   English

将活动类添加到<li>悬停后离开

[英]Add active class to <li> and leave it after hover

I have this code我有这个代码

<script>
    $("li").hover(
      function () {
        $(this).addClass('active');
      }, 
      function () {
        $(this).removeClass('active');
      }
      );
    </script>   

In order to add class active to my li in a menu.为了在菜单中向我的 li 添加活动类。

<ul class="list-first-level">
<div about="" typeof="" class="ds-1col entity entity-paragraphs-item paragraphs-item-modulo-de-enlaces-item view-mode-modulo_de_enlaces_01_d clearfix">
        <li id="elm" class="active always">
            <a href="/grados/eng/">Undergraduate programmes</a>
                <ul>
                    <li>
                        <a href="/grados/eng/ged">Law</a>
                    </li>
                </ul>
        </li>
    </div>
</ul>

I need to not remove the active class after Im not hover on the element.在我没有将鼠标悬停在元素上之后,我不需要删除活动类。

Just use this:只需使用这个:

$("li").hover(function(){
    $(this).addClass("active");
});

Although, you will end up with many active LI and does not provide a good UX.尽管如此,您最终会得到许多活跃的 LI,并且不会提供良好的 UX。

When you hover over an element, remove the 'active' class from all li elements then add it back to the current element.当您将鼠标悬停在一个元素上时,从所有li元素中删除 'active' 类,然后将其添加回当前元素。 This still means that if the user moves away from the last, hovered element - that element will remain in an 'active' state.这仍然意味着如果用户离开最后一个悬停的元素 - 该元素将保持“活动”状态。

<script type="text/javascript">
    $("li").hover(
        function () {
            $("li").removeClass('active');
            $(this).addClass('active');
        }
    );
</script>   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM