使用JavaScript,如果URL中提供了ID,如何突出显示标签

问题描述 投票:0回答:2
<a href="#apple">apple</a>
<a href="#orange">orange</a>

我想要实现的是使用纯js,

  • 突出显示苹果链接如果(window.location.hash)=“ #apple”
  • 突出显示橙色链接如果(window.location.hash)=“ #orange”
javascript html css
2个回答
0
投票

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>

0
投票
首先,您需要使用javascript来获取DOM元素。这可以通过多种方式完成,但为简单起见,我将使用querySelector进行演示。

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.

© www.soinside.com 2019 - 2024. All rights reserved.