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

如何实现滚动时激活input type radio创建的选项列表?

实现滚轮滚动切换Radio选项

保留你的HTML结构不变:

<input type="radio" name="buttons" id="r1" checked>    
<input type="radio" name="buttons" id="r2">    
<input type="radio" name="buttons" id="r3">    
<input type="radio" name="buttons" id="r4">   

<div class="controls">
    <label for="r1"><span></span>LAB & Process Development</label>
    <label for="r2"><span></span>Quality & Regulatory</label>
    <label for="r3"><span></span>Engineering & Project Management</label>
    <label for="r4"><span></span>EHS</label>
</div>

添加以下JavaScript实现滚轮切换逻辑:

// 获取所有radio元素并转为数组
const radios = Array.from(document.querySelectorAll('input[name="buttons"]'));
// 初始选中索引,对应默认checked的radio
let currentIndex = radios.findIndex(radio => radio.checked);

// 监听滚轮事件
document.addEventListener('wheel', (e) => {
    // 可选:阻止页面默认滚动行为,仅触发radio切换
    // e.preventDefault();
    
    // 根据滚动方向更新索引
    if (e.deltaY > 0) {
        // 向下滚动,选中下一个radio
        currentIndex = Math.min(currentIndex + 1, radios.length - 1);
    } else {
        // 向上滚动,选中上一个radio
        currentIndex = Math.max(currentIndex - 1, 0);
    }
    
    // 设置对应radio为选中状态
    radios[currentIndex].checked = true;
});

补充说明

  • 如果只想在特定区域(比如.controls容器内)触发切换,把document换成document.querySelector('.controls')即可。
  • 若需要保留页面正常滚动,删除代码里的e.preventDefault(),此时滚动会同时触发页面滚动和radio切换。
  • 逻辑中加入了边界判断,确保索引不会超出radio列表范围,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:15:35