[英]Is it possible to prevent moving the cursor to the start of an input field when type changes?
我目前正在创建一个密码字段,其中包含在 React/Ionic 中隐藏或显示密码的选项。
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>
问题
如果您要查看链接到的 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
事件之前运行querySelector
或getElementById
引起的问题,这通常是这种情况人们通过 JS 片段在 Internet 上发布。event.stopPropagation()
(在 PayPal 的代码中)或event.preventDefault()
(在您的代码中)的调用是多余且不必要的。 重要的是在更改HTMLInputElement.type
属性的同一事件处理程序中调用input.focus()
。onmousedown
。 'click'
事件适用于所有类型的交互(鼠标、键盘、触摸等),而'mousedown'
和'mouseclick'
事件仅由实际的鼠标输入引发(尽管也经常触摸)。
'click'
并且它被正式定义为PointerEvent
,但它与'mouseclick'
不同,因此您应该想象名称来自屏幕上的按钮“点击”,而不是声音单击物理鼠标按钮。 例如, <button>
的'click'
事件将由用户按下他们的空格键引发。 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.