在这个线程“How to change the link color of the current page with CSS”中,@Taraman 编写了一些被其他人称赞的简洁的 JQuery 函数。现在我尝试使用他的代码,但不幸的是它对我不起作用。我绞尽脑汁想弄清楚为什么他的代码对我不起作用,但我想不通。
如果有人能向我解释他的代码如何工作以及我缺少什么,我将不胜感激。
这是我的 html 代码:
<html>
<head>
<script type="text/javascript" src="../js/jquery.js"></script>
<script> <!--Taraman's code-->
$(document).ready(function() {
$("[href]").each(function() {
if (this.href == window.location.href) {
$(this).addClass("active");
}
});
});
</script>
</head>
<body>
<div id="topnav-bg">
<div id="topnav">
<ul>
<li><a href="../index.html">Home</a></li> <!--dots mean "www.myurlsomething.com"-->
<li><a href="../about.html">About</a></li>
<li><a href="../science.html">Science</a></li>
<li><a href="../adventure.html">Field trip</a></li>
<li><a href="../team.html">Team</a></li>
<li><a href="../biblio.html">Bibliography</a></li>
</ul>
</div>
</div>
</body>
</html>
下面是我的CSS代码:
#topnav-bg {clear:both; background-color:#FAF7C0; }
#topnav ul { margin: 10px 0; padding: 3px 0; }
#topnav ul li { display:inline; }
#topnav ul li a { padding: 0 9px; font: bold 14px Verdana; }
#topnav a:link { color: black; }
#topnav a:visited { color: black; }
#topnav a:hover { color: grey; }
#topnav a:active { color: blue; }
#topnav a:focus { color: blue; }
.active { color: blue; font-weight: bold;}
所以我想用我的代码实现的是,当我在“关于”页面上时,链接/单词“关于”是蓝色的,而其他(家庭、科学……)是黑色的,等等。< br/>
对于你们中的某些人来说,这可能是“简单易懂”的,但我显然遗漏了一些东西。
我想知道 $("[href]").each(function()
这一行是做什么的? "[href]"
应该被其他东西改变吗?
这行 if (this.href == window.location.href)
返回页面位置,对吗?所以在我的例子中,这应该是“www.myurlsomething.com/about.html,对吧?
Taraman 还提到了一些关于 url 参数的事情 if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
。这段代码做了什么以及他指的是什么 url 参数?我应该使用它吗?
我知道这是很多问题,可能是愚蠢的问题。但就像他们说的那样:“没有愚蠢的问题。” :)
感谢您的帮助!
最佳答案
window.location.href
指向您在浏览器的 url 导航栏中看到的 url 路径。
this.href == window.location.href
基本上检查属性 href 值是否等于 url。在您的情况下,即使 this.href
返回绝对路径,它们也可能不相等。
为了使其正常工作,您需要找到匹配的文本实例(此处通过 split()
完成)并将其与 url 进行比较。
$(document).ready(function() {
$("[href]").each(function() {
if (window.location.href.indexOf(this.href.split('/')[this.href.split('/').length - 1]) != -1){
$(this).addClass("active");
}
});
});
关于javascript - JQuery .each函数和改变当前页面链接的CSS [说明],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777298/