[英]Forcing line break in the textarea after 38 characters using jquery
1這是我的代碼,但我不知道如何添加換行符並允許用戶繼續輸入。 帶有警報消息很好,但我只希望用戶繼續鍵入腳本並添加換行符。
dom.query = jQuery.noConflict( true );
dom.query(document).ready(function() {
// var myTA = dom.query('#remaining_chars');
//alert(myTA[0].scrollHeight);
dom.query('#ta').keypress(function() {
var text =dom.query(this).val();
var arr = text.split("\n");
for(var i = 0; i < arr.length; i++) {
if(arr[i].length > 38) {
alert("Not more than 38 characters per line! Continue in next line!");
event.preventDefault(); // prevent characters from appearing
}
}
console.log(text);
dom.query('#ta').val(text);
});
});
鏈接到代碼: http : //jsfiddle.net/e5w5z/8/ 1
如果用戶繼續鍵入並且永不回溯,此代碼將自動插入換行符。 這僅分析文本區域中的最后一行。 因此,如果他們返回到上一行並開始編輯,他們將能夠輸入多於每行所允許的最大字符數。 可以對每一行進行分析,但是您必須編寫一些更復雜的邏輯,以便在更改textarea內容之后在正確的位置插入換行符並正確設置插入記號的位置。
JSFiddle: http : //jsfiddle.net/7V3kY/1/
var LINE_LENGTH_CHARS = 38;
$(function(){
$(document).on('input propertychange','textarea',function(e){
// Something was typed into the textarea
var lines = $(this).val().split("\n");
var last_line = lines[lines.length-1];
if (last_line.length >= LINE_LENGTH_CHARS) {
// Resetting the textarea val() in this way has the
// effect of adding a line break at the end of the
// textarea and putting the caret position at the
// end of the textarea
$(this).val($(this).val()+"\n");
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.