表单提交,页面滚动到必填项位置

复制代码
<body>
    <div style="display:flex;flex-flow: column;">
        
        1<input value="" style="margin:200px; border:1px solid red"></input>
        2<input value="" style="margin:200px; border:1px solid red"></input>
        3<input value="" style="margin:200px; border:1px solid red"></input>
        4<input value="" style="margin:200px; border:1px solid red"></input>
        5<input value="" style="margin:200px; border:1px solid red"></input>
        6<input value="" style="margin:200px; border:1px solid red"></input>
    </div>

    <button onClick="test()">tijiao</button>
    <script>
        function test(){
            const inputs = Array.from(document.getElementsByTagName('input'));
            const emptyIndex = inputs.findIndex(input => input.value === '');
            inputs[emptyIndex].scrollIntoView({behavior: 'smooth'});

        }
    </script>
    </body>

还有使用锚点来实现的方式,比较方便

复制代码
<!DOCTYPE html>
<html>
<head>
    <style>
        /* 用于创建占位符,确保定位不被导航栏等固定元素遮挡 */
        #placeholder {
            display: block;
            height: 100px;
            margin-top: -100px;
            visibility: hidden;
        }
    </style>
</head>
<body>
    <nav>
        <ul>
            <li><a href="#section1">跳转到 Section 1</a></li>
            <li><a href="#section2">跳转到 Section 2</a></li>
            <li><a href="#section3">跳转到 Section 3</a></li>
        </ul>
    </nav>
    <div id="placeholder"></div>
    <section id="section1" style="margin:900px">
        <h2>Section 1</h2>
        <!-- 内容 -->
    </section>
    <section id="section2" style="margin:900px">
        <h2>Section 2</h2>
        <!-- 内容 -->
    </section>
    <section id="section3" style="margin:900px">
        <h2>Section 3</h2>
        <!-- 内容 -->
    </section>
</body>
</html>
相关推荐
像牛奶却不是牛奶4 分钟前
记录几个前端实用小函数
前端·javascript
IDIOT___IDIOT8 分钟前
Windows 解锁后 Chrome 弹出白屏的排查与修复
前端·chrome
tuddy78946420 分钟前
前端应用的离线暂停更新策略:原理、实现与最佳实践
前端
希冀12321 分钟前
【JavaScript】Javascript—JS进阶—Day03
开发语言·javascript·原型模式
hunterandroid31 分钟前
多线程与线程池:从 Thread 到高效并发
前端
光影少年1 小时前
RN 架构:JS层、原生桥接层、原生渲染层 通信原理
开发语言·javascript·架构
用户69371750013841 小时前
AI Agent 里的 Loop 到底是什么?
android·前端·后端
甜美的小天鹅1 小时前
TDD in HTML & JavaScript 概述
javascript·html·tdd
竹林8181 小时前
用 Viem 替代 ethers.js 重写 DeFi 前端:从踩坑 3 天到丝滑体验,我总结了这些关键差异
javascript
hunterandroid1 小时前
内存泄漏与 LeakCanary:从问题定位到修复思路
前端