gpt4 book ai didi

javascript - 将事件类添加到导航中的 ul 列表

转载 作者:行者123 更新时间:2023-11-28 06:28:22 25 4
gpt4 key购买 nike

我正在尝试使用下面的代码片段向我的导航栏添加一个位置指示器(即当选择一个列表项时应该出现一个边框)。目前我的其余 css 代码使用 scss 以 nav{ li{/*code here */} a{/code here/}} 等形式嵌套。当我添加这个事件标签时,没有任何反应。我应该用事件标签以不同的方式格式化吗?有没有更简单的方法来做到这一点?为什么事件标签不起作用?谢谢!!

HTML

<nav class="navbar navbar-main"> 
<ul class="top-menu">
<li id="home"><a href="#">HOME</a></li>
<li id="about"><a href="#about">ABOUT</a></li>
<li id="info"><a href="#media">MEDIA</a></li>
<li id="social"><a href="#social">SOCIAL</a></li>
</ul>
</nav>

CSS

#nav ul li .active {
border-bottom:3px #FFF solid;
}

JS

$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("#nav ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})

最佳答案

对于初学者来说,CSS 没有正确定位元素。您的 css 正在寻找一个 id 为 nav 的元素,该元素不存在。

nav 元素有两个类(navbarnavbar-main),因此您可以使用其中任何一个来开始选择。因为 jquery 将 active 类添加到匹配链接,所以 css 规则需要包含 a。要真正看到边框,您还需要设置一个 display 属性。一个经常使用的是 block 例如:

.navbar ul li a.active {
display:block;
border-bottom:3px #FFF solid;
}

在下面提供的示例中,我更新了 jquery 以针对特定链接,仅用于说明目的。

$(document).ready(function() {
var pgurl = "#about"; //Using a static value for illustration purposes.
$(".navbar ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' ) {
console.log($(this).attr("href"));
$(this).addClass("active");
}
});
});

Fiddle example

关于javascript - 将事件类添加到导航中的 ul 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35140557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com