Javascript 保持当前导航按钮处于活动状态
我的导航菜单中的按钮有以下代码:Javascript 保持当前导航按钮处于活动状态,javascript,html,button,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(){
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
处理程序中的背景色。如果此操作将颜色还原为原来的颜色,请尝试不处理该事件,以查看它是否保持不变
编辑:
将处理程序设置为空字符串看起来不正确。看
编辑:
这样可能更好:
$(this).unbind('mouseleave');
或者(根据上述链接,这是首选方法):
编辑:
为此,您需要删除为onmouseover
和onmouseout
设置的内联处理程序。原因是$(this).off('mouseleave')除非事件与jQuery和$(this.onmouseover=''连接,否则code>将无法工作出于同样的原因,代码>也不起作用
然后需要使用一些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');
};
这样可以确保刚刚设置的颜色保持不变
请注意,jQuery 1.7+是off
语法工作所必需的。如果不需要,为什么要设置mouseout
-事件?请不要在元素属性中使用内联处理程序。这使得代码更难维护。你能更详细地解释一下什么不起作用吗?我发布的示例对我来说效果很好。@EmilDumbazu如果您可以用您尝试过但不起作用的代码编辑您的问题,这也会很有用。
if(url == current ){
changeBGColor(this,'#b90707');changeColor(this,'#fff');
$('.navbtn').off('mouseout');
$('.navbtn').off('mouseover');
};