无法为选定的<a> tag

时间:2017-01-09 12:36:18

标签: javascript html nodelist

I'm working on a full javascript menu.

I'm trying to change the color of <li> or <a> item depending of the offsetTop of the user. Ask me if it's not understandable.

Menu

var menu = document.getElementById('header');
var work = document.getElementById('work');
var who = document.getElementById('who');
var contact = document.getElementById('contact');
var offsetWork = work.offsetTop - 60;
var offsetWho = who.offsetTop - 60;
var offsetContact = contact.offsetTop - 60;
var ul = document.getElementsByTagName('ul')[0];
var li = ul.getElementsByTagName('li');

setInterval(function(){
    var ul = document.getElementsByTagName('ul')[0];
    var li = ul.getElementsByTagName('li');

    if(getCurrPos() >= offsetWork){
        menu.style.display = "block";
    }else if(getCurrPos() <= offsetWork){
        menu.style.display = "none";
    }

    if(offsetWork <= getCurrPos() <= offsetWho){
        li[1].style.backgroundColor = '#00a9c6';
        //li[1].getElementsByTagName('a').style.color = '#fff';
    }else {
        li[1].style.backgroundColor = '#fff';
    }

    if(offsetWho <= getCurrPos() <= offsetContact){
        li[2].style.backgroundColor = '#00a9c6';
        //li[2].getElementsByTagName('a').style.color = '#fff';
    }else {
        li[2].style.backgroundColor = '#fff';
    }

    if(getCurrPos() >= offsetContact){
        li[3].style.backgroundColor = '#00a9c6';
        //li[3].getElementsByTagName('a').style.color = '#fff';
    }else {
        li[3].style.backgroundColor = '#fff';
    }

}, 100);

All the commented line doesn't works and i don't know why because It's finding the [a] item when doing li[1].getElementsByTagName('a');

Thank you for help,

Maël.

1 个答案:

答案 0 :(得分:0)

使用

li[3].querySelector('a').style.color = '#fff';

querySelector返回选择器

选择的所有元素中的第一个Element

getElementsByTagName返回与选择器匹配的所有元素的集合,因此您无法使用 li [2] .getElementsByTagName(&#39; a&#39;)等语法访问该元素.style.color