<a href="#apple">apple</a>
<a href="#orange">orange</a>
我想要实现的是使用纯js,
var loc= window.location.href;
console.log(loc);
values=loc.split('/');
link=values[values.length-1];
var links = document.querySelectorAll("a")
//console.log(links);
links.forEach(links => {
if (links.href.endsWith(link)) {
links.classList.add("active")
}
})
.active{
text-decoration: none;
color: red;
}
<a href="#apple">apple</a>
<a href="#orange">orange</a>
<a href="js">js red</a>
anchors = document.querySelector('a')
因此变量锚将具有上面两个锚的NodeList。让它们变成一个数组。
anchors_array = Array.prototype.slice.call(anchors)
现在,让我们遍历此数组,并进行逻辑检查以查看哈希值是否等同于href。
for(let i = 0; i < anchors_array.length; i++) if(anchors_array[i].href === window.location.hash) // highlight code here.