点击锚点更改DIV Class:兼容changepage类链接+URL页加载自动触发
实现方案
核心调整思路
- 将原有的页面切换逻辑抽离为公共复用函数,同时适配点击触发、页面加载自动触发两个场景
- 扩展事件绑定范围,覆盖顶部导航链接和所有带
changepage类的链接 - 新增页面加载时的URL hash检测逻辑,匹配对应页面自动触发切换
修改后完整代码
// 请确保原有全局变量可正常访问:container、card_items、animation_in、animation_out // 封装公共页面切换函数 function switchToPage(targetId) { const width = $(window).width(); const card_item = $(targetId); // 兼容非导航链接触发的场景:自动匹配对应导航菜单项 const menu_item = $(`.top-menu li a[href="${targetId}"]`).closest('li'); const menu_items = $('.top-menu li'); const d_lnk = $('.lnks .lnk.discover'); if(width >= 1024) { // 仅桌面端执行,且目标页面存在、对应导航项未激活 if(!menu_item.hasClass('active') && $('#home-card').length && card_item.length) { // 关闭所有已打开卡片 menu_items.removeClass('active'); container.find(card_items).removeClass('animated '+animation_in); if($(container).hasClass('opened')) { container.find(card_items).addClass('animated '+animation_out); } // 激活目标页面 menu_item.addClass('active'); container.addClass('opened'); container.find(card_item).removeClass('animated '+animation_out); container.find(card_item).addClass('animated '+animation_in); $(card_items).addClass('hidden'); $(card_item).removeClass('hidden'); $(card_item).addClass('active'); } } } // 绑定点击事件:同时覆盖顶部导航链接和changepage类链接 $(document).on('click', '.top-menu a, a.changepage', function(e) { // 阻止默认锚点跳转 e.preventDefault(); const targetId = $(this).attr('href'); // 仅处理锚点格式的链接 if(targetId.startsWith('#')) { switchToPage(targetId); // 可选:更新URL hash,方便用户分享链接,不需要可删除此行 history.pushState(null, '', targetId); } }); // 页面加载完成后自动检测URL hash触发切换 $(document).ready(function() { const currentHash = window.location.hash; if(currentHash && currentHash.startsWith('#') && $(currentHash).length) { switchToPage(currentHash); } });
补充说明
- 原有代码中的条件判断错误使用了位运算符
&,上述代码已修正为逻辑运算符&&,避免出现逻辑判断异常 - 代码保留了原有仅桌面端(宽度≥1024px)生效的逻辑,不需要该限制可以直接删除宽度判断的条件
- 原有代码中用到的
container、card_items、animation_in、animation_out变量请保持原有的定义位置不变,确保函数内可以正常访问
内容的提问来源于stack exchange,提问作者Joseph Berry
相关产品推荐
相关产品推荐

