我有一个具有单个页眉和页脚的网站,并且在首页和关于页面中包括页眉和页脚,以及活动类的工作方式
<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是唯一的方法吗?
我知道它在那里无法正常运行,所以我给你我的git repo进行克隆:在此处输入链接描述。(虚拟示例)。
注意:
// 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句