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

如何仅用方向键切换背景色 修复单选框切换时h1背景不更新问题

存在的问题

  1. radio选择器语法错误
    你写的const input = document.querySelectorAll('input [type="radio"]')里input和属性选择器之间多了空格,空格代表后代选择器,含义变成「选中input元素内部所有type为radio的元素」,自然匹配不到任何节点,所以你拿不到input的data属性。
  2. keydown事件逻辑错误
    你当前的keydown监听逻辑是:只要按下任意键,就遍历所有radio,依次把每个radio的data-type值设置为主题,最后生效的永远是最后一个radio(third)的值,完全没有判断当前哪个radio是选中状态。
  3. 事件选择不合理
    不需要单独监听keydown事件,radio的change事件本身就会在「点击切换」和「键盘方向键切换」两种场景下触发,直接监听change事件就能覆盖所有交互场景,更符合无障碍设计规范。

修正后的JS代码

const root = document.querySelector(':root')
const toggle = document.querySelectorAll('.radio')
// 修复选择器,去掉input和属性选择器之间的空格
const inputs = document.querySelectorAll('input[type="radio"]')

let theme = 'second';
root.setAttribute('color-scheme', theme)

const loadTheme = theme => {
    root.setAttribute('color-scheme', theme)
}

toggle.forEach(radio =>{ 
    radio.addEventListener('click', () => {
        let theme = radio.getAttribute('data-radio')
        loadTheme(theme)
    })
})

// 监听所有radio的change事件,覆盖点击、键盘切换两种交互
inputs.forEach(radio => {
    radio.addEventListener('change', () => {
        if(radio.checked) {
            const theme = radio.getAttribute('data-type')
            loadTheme(theme)
        }
    })
})

原来的全局keydown监听可以直接删除,修改后h2的背景色会和radio选中状态完全同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:06:03