[英]How to make active class for url while using external header file
我创建了包含所有导航链接的通用 header 文件,并将该文件包含在每个 html 页面中。 这样做时,我想知道是否有办法进行活动页面识别,例如链接的背景等等?
如果您要使用 JS 和没有框架的香草路线,您可以使用location.pathname
并将其与 a 上a
href
匹配。
假设您在https://example.com/about
。
所以,你可以这样做:
document.documentElement.setAttribute('data-path', location.pathname)
然后使用您的 CSS 执行以下操作:
[data-path="/about"] a[href="/about"] {
background-color: yellow;
}
这将匹配页面上的此链接。
<a href="/about">About</a>
不过,如果您使用某种框架,这可能会更直接。
最简单的方法是使用 php。 在外部文件中而不是使用 php 脚本编写class=active
if($page=='home'){echo "active"} 然后它将起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.