1

I have a simple 2 level menu, and the upper menu should get the class "selected" if the mouse is over, and the class should be removed when moving over another first-level menu item. But thats not the problem, that already works.

My problem is: the first-level menuitem should leave on "selected" until i go on another first-level menuitem. Up to now my script removes the class "selected" as soon as i leave my mouse from the item

<script type="text/javascript">
    $(document).ready(function(){
        $("#navi li").hover(function(){
            $(this).addClass('selected');
        },function(){
            $(this).removeClass('selected');
        });
    });
</script>

I want that all items with the class "selected" getting their class removed as soon as my mouse is on another item, but if the mouse is only on a submenu-item or whereever it could be on the page, the selected item should stay selected.

4

3 回答 3

1

这就是你所追求的吗?您可以在悬停时删除所有选定的类,然后将选定的类添加到所需的元素中。

 $(document).ready(function(){
        $("#navi li").hover(function(){
            $("#navi li").removeClass('selected');
            $(this).addClass('selected');
        }
    });
于 2012-04-24T13:34:18.510 回答
0

尝试绑定到mousemove事件:

$("ul").mousemove(function (e) {
    if (e.target.tagName == "LI") {
         $(".selected").removeClass("selected");
         $(e.target).addClass("selected");        
    }
});​

演示。

于 2012-04-24T13:36:40.783 回答
0

发生这种情况是因为以下 lin:

},function(){
                $(this).removeClass('selected');
            });

这意味着当您将鼠标移出时,上述回调将被执行。

而是这样做:

 $(document).ready(function(){
            $("#navi li").hover(function(){
                $(this).addClass('selected');
            },function(){ });
        });

http://jsfiddle.net/SyvYv/

参考http://api.jquery.com/hover/

于 2012-04-24T13:36:59.297 回答