想法:我想在单击特定链接时将 class="active"添加到 li 元素,该链接等于 href 和 url。
问题:我无法选择嵌套在 ul li 内的 href 值。 CSS 可能会提前加载样式。 注意:html 被注入(inject)了 php。
代码:
window.onload = function () {
var curURL = window.location.href.split("/").pop(); //Outputs the current page url ex index.php
var linkNow = document.getElementsByClassName("topnav").getElementsByTagName("a").href;//Nesting this does not work but how can it be achieved?
//Loop check which curURL matches the href value, true->assign active class
for (var i = 0; i < link.length; i++) {
if (curURL == linkNow[i]){
linkNow.addClass("active");
break;
}
}
//As soon as the a element has the class="active" the navbar color will change
}
<ul class='topnav'>
<li><a href='index.php'>Home</a></li>
<li><a href='news.php'>News</a></li>
<li><a href='showcase.php'>Showcase</a></li>
<li class='icon'>
<a href='javascript:void(0);' onclick='myFunction()'>⌨</a><!-- responsive icon-->
</li>
</ul>
最佳答案
有很多种方法可以实现,一种是使用选择器直接获取元素,例如
window.onload = function() {
var href = 'index.php';
var link = document.querySelector('a[href="' + href + '"]');
link.parentNode.className = 'active';
}
.active {
background-color: red;
}
<ul class='topnav'>
<li><a href='index.php'>Home</a></li>
<li><a href='news.php'>News</a></li>
<li><a href='showcase.php'>Showcase</a></li>
</ul>
为了与旧版浏览器兼容,您还可以使用更通用的选择器,例如:
var links = document.querySelectorAll('ul a');
甚至:
var links = document.links;
它与几乎所有浏览器兼容,然后循环它们寻找适当的 href 值。
关于Javascript从子元素中获取剥离的href值(没有jquery)分配事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292498/