静态 html 页面中的菜单处于活动状态 [英] menu active in static html page
本文介绍了静态 html 页面中的菜单处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个只有页眉和页脚的网站,我在主页和关于页面中包含页眉和页脚,活动类如何工作
I have a website with single header and footer, and I include header and footer in home and about pages, how the active class working
<ul>
<li><a class="active" href="">menu1</a></li>
<li><a class="" href="">menu1</a></li>
<li><a class="" href="">menu1</a></li>
</ul>
使用 javascript 和 CSS 是唯一的方法吗?
Is using javascript and CSS the only way?
推荐答案
我知道它在那里不能正常运行所以我给你我的 git repo for clone :在此处输入链接描述.(虚拟示例).
I know it's will not run properly in there so i give you my git repo for clone : enter link description here. (dummy example).
注意:
- 您需要在主机中运行:http://127.0.0.1:5500/index.html..或其他..我运行它与代码(实时服务器)
- 我通过匹配 window.location.pathname 和 href url ..
- 也许有很多方法可以匹配当前路径和标签 url
- 如果您有问题,请发表评论.我也需要为自己的目的解决这个问题
- you need to run in host : http://127.0.0.1:5500/index.html.. or other .. i run it vs code (live server)
- I do it by matching window.location.pathname and a href url ..
- maybe there is many way to match current path a tag url
- if you have issue please comment. also i need to solve this problem for my own purpose
// after page loaded and page refresh this will run to active current <a> tag
window.addEventListener('DOMContentLoaded', (event) => {
activeClass();
});
// after <a> button click
document.querySelectorAll(".btn").forEach(function (btn) {
btn.addEventListener("click", function (e) {
activeClass();
})
})
function activeClass() {
document.querySelectorAll(".btn").forEach(function (btn) {
// get href index.html or about.html or contact.html and add slash (/)
var href = '/' + btn.getAttribute('href');
// get path /index.html or /about.html or /contact.html from current url
var pathname = window.location.pathname;
// check click <a> element that contains .btn class
if (btn.classList.contains('btn')) {
// check a href (/index.html) and current pathname (/index.html) are equal then add active class
if (href == pathname) {
btn.classList.add('active')
console.log('1')
}
}
});
}
<a href="index.html" class="btn ">Home</a>
<a href="contact.html" class="btn ">Contact</a>
<a href="about.html" class="btn ">About</a>
这篇关于静态 html 页面中的菜单处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文