页面加载时如何让激活状态的Anchor标签获取焦点?
问题解决:页面加载时自动让激活状态的锚点获取焦点
问题说明
页面内两个锚点点击可切换对应内容,点击时锚点能正常获取焦点,但页面首次加载时,默认显示的「FOR INSTRUCTORS」锚点无法自动获取焦点,需实现初始化自动聚焦效果。
解决方案
步骤1:给默认激活锚点添加唯一ID
在HTML中为「FOR INSTRUCTORS」锚点增加ID,方便JS精准获取元素:
<a class="insanchor" id="default-active-anchor" href="javascript:void(0)" onclick="showInstructors();">FOR INSTRUCTORS</a>
步骤2:添加初始化聚焦逻辑并优化切换代码
在JavaScript中,等待页面DOM加载完成后调用focus()方法实现默认聚焦,同时统一用hidden类控制内容显示隐藏,避免style属性与class混用,还能在切换时同步转移焦点:
修改后的JavaScript代码:
// 页面DOM加载完成后执行初始化操作 document.addEventListener('DOMContentLoaded', function() { document.getElementById('default-active-anchor').focus(); }); function showInstructors() { const instructorsRow = document.getElementById("ins-container"); const studentsRow = document.getElementById("stu-container"); const insAnchor = document.getElementById("default-active-anchor"); const stuAnchor = document.querySelector(".stuanchor"); // 切换内容显示状态 instructorsRow.classList.remove("hidden"); studentsRow.classList.add("hidden"); // 将焦点转移到当前激活的锚点 insAnchor.focus(); } function showStudents() { const instructorsRow = document.getElementById("ins-container"); const studentsRow = document.getElementById("stu-container"); const insAnchor = document.getElementById("default-active-anchor"); const stuAnchor = document.querySelector(".stuanchor"); // 切换内容显示状态 studentsRow.classList.remove("hidden"); instructorsRow.classList.add("hidden"); // 将焦点转移到当前激活的锚点 stuAnchor.focus(); }
步骤3:统一CSS逻辑(可选)
原CSS中#stu-container直接设置display: none;,可改为通过hidden类控制,保持逻辑一致性:
/* 替换原#stu-container的样式 */ #stu-container.hidden { display: none; }
同时在HTML中给#stu-container默认添加hidden类:
<div id="stu-container" class="hidden">
完成以上修改后,页面加载时「FOR INSTRUCTORS」锚点会自动获取焦点,切换内容时焦点也会同步转移到对应锚点,兼顾交互体验与无障碍访问规范。
内容的提问来源于stack exchange,提问作者Wahid Ahmad Rustaqi
相关产品推荐
相关产品推荐

