使当前导航按钮保持活动状态

时间:2012-10-13 09:10:59

标签: javascript html button

我的导航菜单中的按钮有以下代码:

div onmouseover=\"changeBGColor(this,'#b90707');changeColor(this,'#fff');\" onmouseout=\"changeBGColor(this,'');changeColor(this,'#333');\" onClick="" class='navbtn'>Entry /div

以下代码使元素保持活动状态:

  $('.navbtn').each(function(){
    var path = window.location.href;
    var current = path.substring(path.lastIndexOf('/')+1);
    var url = $(this).attr('onClick').substring(path.lastIndexOf('/')+18,$(this).attr('onClick').length-1);

    if(url == current ){
        changeBGColor(this,'#b90707');changeColor(this,'#fff');
        $(this).onmouseout = '';
        $(this).onmouseover= '';
    };
});       

元素保持活动状态,直到我将鼠标移到元素上。无论我在哪里移动鼠标,我都希望保持活跃状态​​..

1 个答案:

答案 0 :(得分:0)

该代码似乎正在更改onmouseout处理程序中的背景颜色。如果将颜色恢复为原来的颜色,请尝试不处理该事件以查看它是否保持不变。

修改 将处理程序设置为空字符串看起来不正确。见Best way to remove an event handler in jQuery?

修改

这样的事可能会更好:

$(this).unbind('mouseleave'); 

或(根据以上链接,这是首选方法):

$(this).off('mouseleave'); 

修改

要使其生效,您需要删除为onmouseoveronmouseout设置的内联处理程序。这样做的原因是$(this).off('mouseleave');将不起作用,除非事件与jQuery连接,$(this).onmouseover= '';由于同样的原因不起作用。

然后,您需要使用一些jQuery连接事件处理程序:

$('.navbtn').mouseover(function () {
    changeBGColor(this,'#b90707'); 
});

$('.navbtn').mouseout(function () {
    changeBGColor(this, '');
});

现在你正在做的事情:

if(url == current ){ 
    changeBGColor(this,'#b90707');changeColor(this,'#fff'); 
    $(this).onmouseout = ''; 
    $(this).onmouseover= ''; 
}; 

您可以改为:

if(url == current ){ 
    changeBGColor(this,'#b90707');changeColor(this,'#fff'); 
    $('.navbtn').off('mouseout');
    $('.navbtn').off('mouseover'); 
}; 

这应该确保您刚刚设置的颜色保持这种状态。

请注意,off语法可以使用jQuery 1.7+。