简体   繁体   中英

start with active menu item javascript

Hi I'm new and not sure if I'm doing this correctly.

I use Javascript that will decorate an active link after it's been clicked. Question is, how can I load the page with one of the menu items already active?

Example: http://moschalkx.nl/

Javascript code:

function hlite_menu(obj){
    var lnk=document.getElementById('menu').getElementsByTagName('A');
    for(var i in lnk){
        lnk[i].className=(lnk[i]===obj)?'menu_active':'menu_idle';
    }
}

function set_menu(){
    var lnk=document.getElementById('menu').getElementsByTagName('A');
    for(var i in lnk){
        lnk[i].className='menu_idle';
        lnk[i].onclick=function(){
            hlite_menu(this);
        }
    }
}

window.onload=set_menu;

CSS:

a.menu_idle {color:#333333; text-decoration:none;}
a.menu_active {color:#333333; text-decoration:underline;}
a:visited {color:#333333; text-decoration:none;}
a:hover {color:#333333; text-decoration:underline;}

You already have your hlist_menu function that sets a particular link to be active, so I would just call that from your set_menu function for whichever link is supposed to be active to begin with

function set_menu(){
    var lnk=document.getElementById('menu').getElementsByTagName('A');
    for(var i in lnk){
      lnk[i].className='menu_idle';lnk[i].onclick=function({hlite_menu(this);}}

      if (lnk[i] /* ??? how do you know whether this is the link to activeate up front? */ ) {
          hlist_menu(lnk[i]);
      }
    }

Also, this

lnk[i].onclick=function({hlite_menu(this);}}

can be simplified to just

lnk[i].onclick = hlite_menu;

assuming you change it to

function hlite_menu(){
    var lnk= document.getElementById('menu').getElementsByTagName('A');
    for(var i in lnk){
       lnk[i].className = (lnk[i] === this) ? 'menu_active':'menu_idle';
    }
}

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