原生js标识当前导航位置(给当前导航一个className=active)

导航html结构为:

<div class="header2-nav">
<a href="index.html">首页</a>
<a href="course.html">课程page</a>
<a href="teach.html">教学page</a>
<a href="booking.html">预约page</a>
<a href="location.html">校区page</a>
</div>

当前页面的url地址例子:http://testXXX.com/index.html

let urlArr = window.location.href.split('/')
let current = urlArr[urlArr.length-1] //最后一个斜杠后面的导航标识
//let navArr = ['index.html','course.html','teach.html','booking.html','location.html']

let nav = document.getElementsByClassName('header2-nav')[0].children
let navArr = []

// 获取导航里面的所有的href的属性值
for(let i = 0;i<nav.length;i+=1){
navArr[i] = nav[i].attributes[0].nodeValue
}

//遍历导航数组与当前匹配的的导航加标示className
navArr.forEach((value,index)=>{
if(value.indexOf(current) === 0){ //导航后面可能会有锚点不能用===
document.getElementsByClassName('header2-nav')[0].children[index].className='active'
}
})

原文地址:https://www.cnblogs.com/keleyz/p/10490258.html