簡體   English   中英

文本區域限制輸入按下並從新行中修剪空白

[英]Textarea limit enter pressed & trim the white space from new line

抱歉,我是 JavaScript 新手,目前我面臨着用戶復制包含大量換行符的文章時遇到的問題。 我怎樣才能修剪它並使它只有 1 條新線? 以及如何限制用戶按回車鍵(換行)?

例如,當從其他來源復制一些文本並粘貼到 textarea 時,它將顯示如下:

This is 
                    //new line 
                   //new line  
                   //new line 
                  //new line 
                  //new line     
Orange
                  //new line 
                  //new line   
                  //new line  
Not apple

復制到textarea/從textarea輸入后如何制作

This is 

orange

not apple

小提琴演示 =小提琴

my fiddle output :
------------------ 
This is 
Orange
not apple

Expected output : 
-----------------
This is 

Orange

not apple

任何幫助將不勝感激。 謝謝!

如果我對您的理解正確,您可以通過添加偵聽器按Enter鍵來防止用戶插入換行符。 像這樣的東西:

var textarea = document.getElementById("myTextArea");
textarea.addEventListener("keydown", function (e) {
    if (e.keyCode == 13) { // keyCode 13 corresponds to the Enter key
        e.preventDefault(); // prevents inserting linebreak
    }
});

JSFiddle在這里

至於替換字符串中的多個新行,正如@adeneo 在注釋中所指出的,您可以使用 JavaScript 的string.replace()函數。 您可以在偵聽paste事件的textarea上添加另一個偵聽器,如下所示:

textarea.addEventListener("paste", handler);

其中handler是一個您可以定義的函數,用於清除換行符。 這是一個顯示這個的小提琴: JSFiddle

您的文本需要兩個 \\n。 檢查我的答案,我用 jquery 和沒有 jquery 顯示它。 據我了解,您可以通過模糊功能實現您的要求。

 $("#withjquery").blur(function(){ $("#withjquery").val(($("#withjquery").val().replace(/\\n\\s*\\n/g, '\\n\\n'))); }); function doFormat() { document.getElementById("withoutjquery").value = document.getElementById("withoutjquery").value.replace(/\\n\\s*\\n/g, '\\n\\n'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <textarea id="withjquery" name="withjquery" rows="5" cols="40" ></textarea> <textarea id="withoutjquery" name="withoutjquery" rows="5" cols="40" onblur="doFormat()" ></textarea>

暫無
暫無

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

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