如何用JavaScript实现点击单选/复选框后滚动到下一个div
披萨选择弹窗滚动逻辑完善方案
核心逻辑
- 单选按钮触发:点击后直接定位并滚动到下一个选项组
- 复选框触发:仅当当前组选中数量达到预设上限时,才滚动到下一个选项组
匹配需求的典型HTML结构
<div class="pizza-modal"> <!-- 饼底选择组(单选) --> <div class="option-group" data-index="0"> <h3>选择饼底</h3> <ul> <li><input type="radio" name="crust" value="thin"> 薄底</li> <li><input type="radio" name="crust" value="thick"> 厚底</li> <li><input type="radio" name="crust" value="stuffed"> 芝心底</li> </ul> </div> <!-- 配料选择组(复选,上限2个) --> <div class="option-group" data-index="1" data-max="2"> <h3>选择配料</h3> <ul> <li><input type="checkbox" name="topping" value="pepperoni"> 意大利辣香肠</li> <li><input type="checkbox" name="topping" value="mushroom"> 蘑菇</li> <li><input type="checkbox" name="topping" value="olive"> 橄榄</li> <li><input type="checkbox" name="topping" value="bacon"> 培根</li> </ul> </div> <!-- 尺寸选择组(单选) --> <div class="option-group" data-index="2"> <h3>选择尺寸</h3> <ul> <li><input type="radio" name="size" value="small"> 小份</li> <li><input type="radio" name="size" value="medium"> 中份</li> <li><input type="radio" name="size" value="large"> 大份</li> </ul> </div> </div>
完善后的JavaScript代码
// 获取所有选项组容器 const optionGroups = document.querySelectorAll('.option-group'); // 滚动到下一个选项组的通用方法 function scrollToNextGroup(currentGroup) { const currentIndex = parseInt(currentGroup.dataset.index); const nextGroup = optionGroups[currentIndex + 1]; if (nextGroup) { nextGroup.scrollIntoView({ behavior: 'smooth', // 平滑滚动效果 block: 'start' // 目标元素顶部对齐视口 }); } } // 绑定单选按钮点击事件 document.querySelectorAll('input[type="radio"]').forEach(radio => { radio.addEventListener('click', function() { const currentGroup = this.closest('.option-group'); scrollToNextGroup(currentGroup); }); }); // 绑定复选框点击事件 document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => { checkbox.addEventListener('click', function() { const currentGroup = this.closest('.option-group'); const maxSelection = parseInt(currentGroup.dataset.max); // 统计当前组已选中的复选框数量 const selectedCount = currentGroup.querySelectorAll('input[type="checkbox"]:checked').length; // 达到选择上限时触发滚动 if (selectedCount === maxSelection) { scrollToNextGroup(currentGroup); } }); });
关键细节说明
closest('.option-group'):精准定位当前输入框所属的选项组容器,避免DOM层级变动导致逻辑失效data-index:标记选项组顺序,快速定位下一个目标元素data-max:自定义属性存储复选框组的选择上限,无需硬编码,适配不同组的需求scrollIntoView:原生API实现滚动,兼容性好且无需额外依赖
内容的提问来源于stack exchange,提问作者Ronit
相关产品推荐
相关产品推荐

