簡體   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