[英]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.