使用JavaScript实现菜单当前页面激活状态显示
问题解决方法
你的问题出在首页URL的多种形式和菜单链接的href不完全匹配:首次打开首页时,URL可能是https://xxx.com、https://xxx.com/或https://xxx.com/index.html中的一种,但你的判断条件要求document.location.href和菜单链接的href完全相等,一旦两者形式不一致(比如首页链接写的是/,但实际URL是/index.html),就无法触发激活样式。
下面给你几种可行的修改方案:
方案1:兼容首页的多种URL形式
直接针对首页做特殊判断,覆盖常见的首页URL格式:
$(function(){ $('.header-nav a').each(function(){ const currentUrl = document.location.href; const linkUrl = this.href; // 判断是否是首页场景 const isHomePage = currentUrl === 'https://你的域名.com' || currentUrl === 'https://你的域名.com/' || currentUrl === 'https://你的域名.com/index.html'; const isHomeLink = linkUrl === 'https://你的域名.com' || linkUrl === 'https://你的域名.com/' || linkUrl === 'https://你的域名.com/index.html'; // 要么完全匹配,要么是首页场景 if(currentUrl === linkUrl || (isHomePage && isHomeLink)){ $(this).addClass('header-nav__item__active'); } }); });
方案2:基于路径匹配(更通用)
只对比URL的路径部分(去掉域名),避免域名、斜杠、index.html带来的差异:
$(function(){ $('.header-nav a').each(function(){ // 获取当前页面的路径(比如 / 或 /index.html) const currentPath = document.location.pathname; // 获取链接的路径 const linkPath = new URL(this.href).pathname; // 兼容首页的路径形式 const isHomeMatch = (currentPath === '/' || currentPath === '/index.html') && (linkPath === '/' || linkPath === '/index.html'); // 路径完全匹配,或者是首页场景 if(currentPath === linkPath || isHomeMatch){ $(this).addClass('header-nav__item__active'); } }); });
方案3:简洁的后缀判断
通过判断URL的后缀来兼容首页的不同形式:
$(function(){ $('.header-nav a').each(function(){ const currentUrl = document.location.href; const linkUrl = this.href; // 处理完全匹配、首页斜杠和index.html的情况 if(currentUrl === linkUrl || (currentUrl.endsWith('/') && linkUrl === currentUrl.slice(0, -1)) || (currentUrl.endsWith('/index.html') && (linkUrl === currentUrl.slice(0, -11) || linkUrl === currentUrl.slice(0, -11)+'/'))){ $(this).addClass('header-nav__item__active'); } }); });
你可以根据自己网站的实际URL格式选择其中一种方案,修改后首次打开首页时,菜单就能正常显示激活样式了。
内容的提问来源于stack exchange,提问作者Анна Прихненко
相关产品推荐
相关产品推荐

