簡體   English   中英

如何防止 cursor 在固定列 textarea 中跳轉到下一行

[英]How to prevent cursor jump to next line in fixed column textarea

我有一個帶有以下 HTML 的文本區域...

 <textarea id="inputFreeContentArea" cols="16" rows="6" maxlength="96" wrap="hard"></textarea>

當用戶輸入文本時,我希望 cursor 在一行輸入 16 個字符時停止移動,它不應該自動移動到下一行,只有當用戶按下回車鍵時。 此外,不應超過 6 行。

如何才能做到這一點?

沒有一種簡單的方法可以實現您想要的,這需要大量的代碼和輸入檢查。 相反,您可以使用包裝器和六個input元素,對它們進行一些樣式設置,然后將值收集到隱藏的輸入前。 實時或在表單驗證器中。 像這樣的東西:

 function createTxtarea(parent, cols) { // Set the cols of the "textarea" const inputs = parent.querySelectorAll('input'); inputs.forEach(input => input.setAttribute('maxlength', cols)); // Add listener for Enter and ArrowUp/down keys const focusTo = { Enter: (e) => e.target.nextElementSibling, ArrowDown(e) {return this.Enter(e);}, ArrowUp: (e) => e.target.previousElementSibling }; parent.addEventListener('keydown', (e) => { const key = e.key; if (typeof focusTo[key] === 'function') { e.preventDefault(); const prext = focusTo[key](e); if (prext) prext.focus(); } // Collect the value here if needed }); } createTxtarea(document.getElementById('area1'), 16);
 .txtarea { border: 1px solid #ccc; padding: 1px; display: inline-block; }.txtarea input { border: none; display: block; }
 <form> <div id="area1" class="txtarea"> <input type="text" name="area1[]"> <input type="text" name="area1[]"> <input type="text" name="area1[]"> <input type="text" name="area1[]"> <input type="text" name="area1[]"> <input type="text" name="area1[]"> <input type="text" name="area1[]"> </div> </form>

使用[]為輸入名稱添加后綴使它們可以作為后端的數組使用,這樣您也可以輕松地從服務器的輸入中提取單個值。

您可以改進基本代碼。 創建多個“txtareas”很容易,如果需要,可以將代碼轉換為OOP,並且可以動態創建輸入甚至父元素。

該代碼在手機中被忽略,但填寫“txtarea”仍然很流暢。 如果您將maxlength屬性添加到 HTML,如果 JS 關閉,“txtarea”將比自定義的真實 textarea 元素更流暢地工作。

暫無
暫無

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

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