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

如何根据可见性获取querySelectorAll选中的OTP输入框元素?

解决方案

你可以通过筛选querySelectorAll返回的NodeList,找到当前可见的输入框元素来解决这个问题。以下是两种可行的实现方式:

方式一:直接筛选可见元素

利用offsetParent属性判断元素是否可见(当元素设置display: none时,offsetParent会返回null),在setOtpInputValue函数中添加筛选逻辑:

let codeBox1 = document.querySelectorAll(".codeBox1");
let codeBox2 = document.querySelectorAll(".codeBox2");
let codeBox3 = document.querySelectorAll(".codeBox3");
let codeBox4 = document.querySelectorAll(".codeBox4");

let OTPdigits = null;

const setOtpInputValue = () => {
    // 定义工具函数,从NodeList中获取可见元素
    const getVisibleInput = (nodeList) => {
        return Array.from(nodeList).find(el => el.offsetParent !== null);
    };

    // 获取每组中可见的输入框,拼接值
    OTPdigits = getVisibleInput(codeBox1).value + 
                getVisibleInput(codeBox2).value + 
                getVisibleInput(codeBox3).value + 
                getVisibleInput(codeBox4).value;
}

如果你的隐藏逻辑是用visibility: hidden,可以把判断条件换成:

return Array.from(nodeList).find(el => {
    const style = window.getComputedStyle(el);
    return style.visibility !== 'hidden' && style.display !== 'none';
});

方式二:通过父容器分组优化(更高效)

给两组OTP输入框分别添加父容器并标记,比如邮箱OTP的父容器加class="otp-group active",手机OTP的加class="otp-group"(切换可见时更新active类),这样可以先找到可见的父容器,再获取内部的输入框,避免多次筛选:

<!-- 邮箱OTP容器 -->
<div class="otp-group active">
    <input class="codeBox1" type="text">
    <input class="codeBox2" type="text">
    <input class="codeBox3" type="text">
    <input class="codeBox4" type="text">
</div>

<!-- 手机OTP容器 -->
<div class="otp-group">
    <input class="codeBox1" type="text">
    <input class="codeBox2" type="text">
    <input class="codeBox3" type="text">
    <input class="codeBox4" type="text">
</div>

对应的JS代码:

let OTPdigits = null;

const setOtpInputValue = () => {
    // 先找到可见的OTP组(假设用active类标记可见状态)
    const visibleOtpGroup = document.querySelector('.otp-group.active');
    
    // 从可见组内获取输入框
    const codeBox1 = visibleOtpGroup.querySelector('.codeBox1');
    const codeBox2 = visibleOtpGroup.querySelector('.codeBox2');
    const codeBox3 = visibleOtpGroup.querySelector('.codeBox3');
    const codeBox4 = visibleOtpGroup.querySelector('.codeBox4');
    
    OTPdigits = codeBox1.value + codeBox2.value + codeBox3.value + codeBox4.value;
}

这种方式逻辑更清晰,也减少了DOM查询的次数,推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:20:40