簡體   English   中英

如何更改數字輸入元素的文本方向?

[英]How can I change the text direction of a number input element?

我可以有一個數字輸入元素,其中數字是從右到左輸入的,中間沒有手動移動 cursor 嗎? 該應用程序用於訓練基本心算,其中順序更自然。

我還想將輸入元素配置為數字。 在桌面上自動添加步進按鈕和在移動設備上選擇數字鍵盤都是有益的。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange寫道:

請注意,根據WHATWG forms 規范selectionStartselectionEnd屬性和setSelectionRange方法僅適用於文本、搜索、URL、電話和密碼類型的輸入。 Chrome,從版本 33 開始,在訪問輸入類型 rest 上的那些屬性和方法時拋出異常。 例如,對於數字類型的輸入:“無法從‘HTMLInputElement’讀取‘selectionStart’屬性:輸入元素的類型(‘數字’)不支持選擇”。

事實上,雖然我可以很容易地獲得我想要的文本輸入,但在最近的帶有數字輸入元素的 Chrome 上,它對我來說失敗了,如下面的演示所示。 對於數字輸入元素,當前選擇端點始終為null

有什么辦法可以解決這些限制並操縱數字元素的 cursor / 插入符號 position 嗎? 或者,除此之外,有什么方法可以使文本元素拒絕非數字輸入、顯示步進器並使用數字鍵盤,最好不要鏈接到像 Angular 這樣的重庫依賴項?

 const dbg = document.getElementById("dbg"); ["txt", "num"].forEach(id => { const elt = document.getElementById(id); elt.addEventListener("input", evnt => { dbg.innerText = `evnt.inputType = ${evnt.inputType}, elt.selectionStart = ${elt.selectionStart}, elt.selectionEnd = ${elt.selectionEnd}`; if (evnt.inputType == "insertText" && elt.selectionStart === 1 && elt.selectionEnd === 1) { elt.setSelectionRange(0, 0); } }); });
 <p>Text: <input type="text" id="txt"></p> <p>Number: <input type="number" id="num"></p> <p>Debug: <span id="dbg"></span></p>

您可以使用 CSS 來做到這一點。

<p>Text: <input type="text" id="txt" style="direction: rtl"></p>
<p>Number: <input type="number" id="num" style="direction: rtl"></p>
<p>Debug: <span id="dbg" ></span></p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM