You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按下箭头键时用jQuery移除元素inert属性的实现问题

问题解决:按下向下箭头移除对应section的inert属性

你的代码存在几个关键问题,导致功能无法正常触发,以下是修正方案:

问题分析

  • document.querySelectorAll('.h-trigger:focus')仅会选取页面加载时已聚焦的元素,页面初始化时没有元素处于聚焦状态,因此事件根本绑定不上
  • 事件回调里的this指向错误,且混用原生JS和jQuery逻辑,容易出现上下文混乱
  • HTML中tabindex=0"多了一个冗余双引号,属于语法错误

修正后的代码

原生JS版本(推荐,无需依赖jQuery)

// 给所有.h-trigger元素绑定键盘事件
document.querySelectorAll('.h-trigger').forEach(el => {
    el.addEventListener("keydown", e => {
        // 校验:按下的是向下箭头,且当前元素处于聚焦状态
        if (e.key === "ArrowDown" && el === document.activeElement) {
            const nextSection = el.nextElementSibling;
            // 确认下一个元素是目标.section后再移除inert
            if (nextSection && nextSection.classList.contains('section')) {
                nextSection.removeAttribute("inert");
            }
        }
    });
});

jQuery版本(若必须使用jQuery)

$('.h-trigger').on('keydown', function(e) {
    if (e.key === "ArrowDown") {
        $(this).next('.section').removeAttr('inert');
    }
});

额外修正的HTML语法

<h2 class="h-trigger" tabindex="0">Heading 1</h2>
<div class="section" inert>
Something here
</div>

<h3 class="h-trigger" tabindex="0">Heading 2</h3>
<div class="section" inert>
Something else here
</div>

内容的提问来源于stack exchange,提问作者DeanH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:35:09