繁体   English   中英

当类型更改时,是否可以防止将 cursor 移动到输入字段的开头?

[英]Is it possible to prevent moving the cursor to the start of an input field when type changes?

我目前正在创建一个密码字段,其中包含在 React/Ionic 中隐藏或显示密码的选项。

  • 当您更改输入的类型时,我想将注意力集中在密码字段上 (就像PayPay 登录页面一样)我在mousedown -Event 上使用event.preventDefault()进行操作。

 const input = document.querySelector('input') function toggleVisibility() { if (input.type === "text") input.type = "password" else input.type = "text" } function keepFocus(event) { event.preventDefault() }
 <input placeholder="Password" type="text"> <button onmousedown="keepFocus(event)" onclick="toggleVisibility()">Show Password</button>

问题

  • 当我更改输入字段的类型时, cursor 会翻转回输入字段的开头 我想将 cursor 保留在原来的位置。 (再次像PayPal一样)

如果您要查看链接到的 PayPal 自己的代码,您会发现这只是在单个事件侦听器中调用input.focus()的问题:

 function hidePassword(e) { if (baseType === 'tel') { $(field).addClass('tel-password'); } else { field.setAttribute('type', 'password'); } $(btnShow).removeClass('hide'); $(btnHide).addClass('hide'); field.focus(); e.stopPropagation(); login.logger.log({ evt: 'is_pwd_sh', data: 'N', instrument: true }); login.logger.pushLogs(); }

可以将其简化为下面的示例,并进行一些更改:

  • 默认type=""应始终为password 用户希望密码输入不会突然显示密码——他们正在向所有可以看到他们屏幕的人输入密码(尤其是在屏幕共享或投影到电视或进行演示等时)。
  • 我已将querySelector调用更改为在<button data-for="" />中嵌入目标<input type="password" /> /> 以避免在DOMContentLoaded事件之前运行querySelectorgetElementById引起的问题,这通常是这种情况人们通过 JS 片段在 Internet 上发布。
  • event.stopPropagation() (在 PayPal 的代码中)或event.preventDefault() (在您的代码中)的调用是多余且不必要的。 重要的是在更改HTMLInputElement.type属性的同一事件处理程序中调用input.focus()
  • 避免使用带有按钮的onmousedown 'click'事件适用于所有类型的交互(鼠标、键盘、触摸等),而'mousedown''mouseclick'事件仅由实际的鼠标输入引发(尽管也经常触摸)。

 function toggleVisibilityOnClick( event ) { const button = event.currentTarget; const input = document.getElementById( button.dataset['for'] ); if(.input ) throw new Error( "Couldn't find password input;" ). if( input.type === 'text' ) { input;type = 'password'. } else { input;type = 'text'. } input;focus(); }
 <input placeholder="Password" type="password" id="pwdInp" /> <button data-for="pwdInp" onclick="toggleVisibilityOnClick(event)">Show Password</button>


Microsoft 的浏览器具有-ms-reveal ,这使您的切换变得多余,因此在这种情况下您应该隐藏切换:

@supports selector(::-ms-reveal) {
    
    input[type="password"] + button[data-for] {
        display: none;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM