1. 實現換行的想法是,監聽Enter按鍵, 找到光標當前所在位置,在當前位置上插入一個“\r\n”,
2. 實現提交:監聽Ctrl + enter鍵,找到父級form,提交Form
$('#inputmessage').keypress(function (ev) {
// 監聽按鍵
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (ev.ctrlKey && (keycode == 13 || keycode == 10)) {
insertNewlineToChat($(this));
}
else if (!ev.ctrlKey && (keycode == 13 || keycode == 10)) {
$(this).closest("form").submit();
return false;
}
return true;
});
function insertNewlineToChat(element) {
var myValue = "\r\n";
var $t = $(element)[0];
if (document.selection) {
$t.focus();
var sel = document.selection.createRange();
sel.text = myValue;
$t.focus();
sel.moveStart('character', -l);
} else if ($t.selectionStart || $t.selectionStart == '0') {
var startPos = $t.selectionStart;
var endPos = $t.selectionEnd;
var scrollTop = $t.scrollTop;
$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
$t.focus();
$t.selectionStart = startPos + 1;
$t.selectionEnd = startPos + 1;
$t.scrollTop = scrollTop;
} else {
$t.value += myValue;
$t.focus();
}
}
insertNewlineToChat函數參考了 水墨寒 的文本框插入表情控件: http://www.jq-school.com/Detail.aspx?id=153