[英]Keep the current nav button active
我的导航菜单中有一个按钮的以下代码:
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= '';
};
});
该元素保持活动状态,直到我将鼠标移到该元素上为止。 无论何时将鼠标移至何处,我都希望保持活跃状态。
该代码似乎正在onmouseout
处理程序中更改背景颜色。 如果这将颜色恢复为原来的颜色,请尝试不处理该事件以查看其是否保持不变。
编辑:将处理程序设置为空字符串看起来不正确。 请参阅在jQuery中删除事件处理程序的最佳方法?
编辑:
这样的事情可能会更好:
$(this).unbind('mouseleave');
或者(根据以上链接,这是首选方法):
$(this).off('mouseleave');
编辑:
为此,您将需要删除为onmouseover
和onmouseout
设置的内联处理程序。 原因是$(this).off('mouseleave');
除非事件通过jQuery和$(this).onmouseover= '';
连接起来,否则它将无法正常工作$(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+。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.