[英]highlight in different colors for links in main menu based on current page
如何根据当前页面突出显示主菜单中每个链接的不同颜色?
例如,当前页面与我们联系时,将主菜单中的contact us链接颜色更改为红色
当当前页面是关于我们的时候,在主菜单中将about us链接颜色更改为橙色,依此类推
您可以使用javascript执行此操作:
首先,检索当前的url路径:
var pathname = window.location.pathname;
例如,返回“/contact.html”然后您可以使用此值来确定哪个项目是高亮的:
if(pathname == "/contact.html"){
document.getElementById("contact").addClass("hilighted");
}
等等。
a:active
:当您单击链接并按住它时。
a:visited
:链接已被访问时。
如果您希望突出显示与当前页面对应的链接,您可以为链接定义一些特定样式 -
.current {
color: red;
background-color: #000000;
}
在服务器端或客户端(使用javascript / jquery)将此新类.current
仅添加到相应的li
(链接)。
使用JQuery,您可以使用.each函数通过以下代码迭代链接:
$(document).ready(function() {
$("[href]").each(function() {
if (this.href == window.location.href) {
$(this).addClass("current");
}
});
});
根据您的页面结构和使用的链接,您可能需要缩小选择范围,例如:
$("nav [href]").each ...
如果您使用url参数,可能需要剥离这些:
if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
这样您就不必编辑每个页面。
有很多方法,很难说没有看到你的代码哪个是最好的。
您可以在每个页面上使用一些Javascript来添加或更改链接的类。
例如,在您的联系我们页面上使用类似的脚本
var contactLink = document.getElementById("contactUs");
contactLink.addClass("orangeLink");
您可以根据当前页面将活动类添加到菜单中。
如果你在联系页面然后添加活动类来联系我们菜单,同样关于我们页面,然后为该活动类做一些css。
例如,如果您在联系我们页面,那么: -
<ul>
<li class="home"><a href="home.html">Home</a></li>
<li class="contact active"><a href="contact-us.html">Contact Us</a></li>
<li class="about"><a href="about.html">About Us</a></li>
</ul>
现在为此做一些css: -
.contact.active{
color : red;
}
.about.active{
color : orange;
}
它会对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.