点击按钮后移除其焦点,将文档设为当前激活元素的实现方案
问题描述
我在网页里做了一个restart按钮,想要实现的效果是:用户点击按钮后,把当前的"active"元素切换成整个document,而不是按钮本身。现在的问题是,点击按钮后按空格键,会触发按钮的点击事件(因为按钮处于激活状态),我希望点击后取消按钮的激活状态,让空格键的操作被document捕获,而不是按钮。
一开始我尝试点击后禁用按钮,但这样按钮之后就没法用了,所以想找其他办法。
现有代码
JavaScript代码
$(".restart").on("click", function(){ //stop the ongoing timer; start new timer when key pressed again clearInterval(stopTime); time_limit = 30; flag = 1; textIndex = 0; newTextArray = []; correct = 0, wrong = 0, total = 0; $('.typingContent').html(typingText); $("#timer").text('start typing to start the time'); const { activeElement } = document; if (activeElement) { activeElement.blur(); } })
HTML代码
<%- include ("partials/header") -%> <h1>Typet - Typing Game!</h1> <h3 id="timer">start typing to start the timer</h3> <div class="container"> <div class="timer"> </div> <p class="typingContent"><%= typingContent %></p> <button name="restart" value="submit" class="restart">restart</button> </div> <%- include ("partials/footer") -%>
解决方案
方法1:优化焦点处理,让页面根元素获取焦点
你已经用到了activeElement.blur(),但只执行blur可能不够,需要主动让页面元素获取焦点:
- 先给HTML的
<body>标签添加tabindex="-1"属性,让它可以接收焦点:
<body tabindex="-1">
- 修改JS中的焦点处理代码:
// 取消当前激活元素的焦点 if (document.activeElement) { document.activeElement.blur(); } // 让body获取焦点,替代按钮成为active元素 document.body.focus();
方法2:阻止按钮点击时自动获取焦点
直接监听按钮的mousedown事件并阻止默认行为,这样点击按钮时它不会自动获得焦点,也就不会触发空格键的点击事件:
$(".restart").on("mousedown", function(e) { e.preventDefault(); });
这种方式不需要修改其他元素,按钮依然可以正常响应点击逻辑。
方法3:转移焦点到隐藏元素
创建一个隐藏的可聚焦元素,点击按钮后将焦点转移过去,既不会影响页面视觉,也能让按钮失去激活状态:
- 在HTML中添加隐藏元素:
<div id="hidden-focus" tabindex="-1" style="position: absolute; left: -9999px; top: -9999px;"></div>
- 修改JS中的焦点处理代码:
if (document.activeElement) { document.activeElement.blur(); } // 转移焦点到隐藏元素 document.getElementById('hidden-focus').focus();
内容的提问来源于stack exchange,提问作者BlazeRod11
相关产品推荐
相关产品推荐

