简体   繁体   中英

How to change menu li class when div changes

I'm working on a one-page site that has several "articles". Each div has class "article" and id "first", "second", "third", etc. I have a standard menu:

<ul id="nav">
  <li id="n1"><a href="#first"></a></li> 
  <li id="n2"><a href="#second"></a></li>
  <li id="n3"><a href="#third"></a></li>
  //...etc             
</ul>

What I need to do is assign the class "active" to the li tag w/id n1 when the current article has id "first" (and unassign active class from all other li tags); assign active class to li tag w/id n2 when current article has id "second"; etc.

I would appreciate any help... I'm really stuck on this one. TIA for your help.

PS I'm using the following code to, in essence, assign an active class to the currently viewed article:

$('#first, #second, #third, ...).bind('inview', function (event, visible) {
        if (visible == true) {
        $(this).addClass("inview");     
        } else {
        $(this).removeClass("inview");
        }   
});

There are more ways to do it. This is one, which may give you ideas:

var navrefs= document.getElementById('nav').getElementsByTagName('a');
for (var i=0, len = navrefs.length;i<len;i++){
  if (location.hash == navrefs[i].href){
     navrefs[i].parentNode.className = 'active'; 
  } else {
     navrefs[i].parentNode.className = ''; 
  }
}

Here's an example of the following →

The following assumes you have the class current on your currently active article page:

var articles = document.getElementsByClassName('article'),
    al = articles.length,
    which, i;

for (i = 0; i < al; i++) {
    if (/current/.test(articles[i].className)) {
        which = articles[i].id;
    }
}

var atags = document.getElementsByTagName('a'),
    al2 = atags.length;

for (i = 0; i < al2; i++) {
    if (atags[i].href.search(which) > -1) {
        atags[i].parentNode.className = 'active';
    } else {
        atags[i].parentNode.className = '';
    }
}

Since it's to achieve a CSS effect, why not just right CSS like this:

.first #n1,
.second #n2,
.third #n3,
...etc 
 {
   CSS for active article
}

and then just make the JS in charge of setting the appropriate class on the wrapper/body, eg

<li id="n1"><a href="#first" onclick="setC('first')"></a></li>
etc.
...
function setC(str){
    document.getElementById('wrapper').className=str;
}

This would would reduce the demand on the JS engine

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