简体   繁体   中英

Keep the current nav button active

I have the following code for a button in my nav menu:

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

And the following code to keep the element active:

  $('.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= '';
    };
});       

The element remains active until i move the mouse over the element. I would like to remain active anytime no matter where i move my mouse on..

That code appears to be changing the background color in the onmouseout handler. If this reverts the color to what it was, try not handling that event to see if it stays the same.

Edit: Setting the handler to the empty string doesn't look right. See Best way to remove an event handler in jQuery?

Edit:

Something like this might be better:

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

Or (according to the above link, this is the preferred approach):

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

Edit:

For this to work you will need to remove the inline handlers you have set up for onmouseover and onmouseout . The reason for this is that $(this).off('mouseleave'); won't work unless the events are wired up with jQuery, and $(this).onmouseover= ''; won't work either for the same reason.

You will then need to wire up the event handlers with some jQuery:

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

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

Now where you are currently doing:

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

You can instead do:

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

Which should ensure that the colors you have just set stay that way.

Note that jQuery 1.7+ is required for the off syntax to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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