0%

Div Contenteditable 支持 Enter / Ctrl+Enter 换行

网站找了不少代码,但总有点问题,最后拼拼凑凑,终于实现了。
模拟微信,支持Ctrl+Enter换行,Enter发送,测试环境win7+chrome,mac+chrome

核心部分代码如下,其他的代码可以点击示例查看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
$('div[contenteditable="true"]').keypress(function(e) {

console.log(e.keyCode)

if (e.keyCode == 13 && !e.ctrlKey) {
console.log("enter")
e.preventDefault();
return false;
} else if (e.keyCode == 10 || (e.keyCode == 13 && e.ctrlKey)) {
console.log("ctrl + enter");
e.preventDefault();

var docFragment = document.createDocumentFragment();

//add a new line
var newEle = document.createTextNode('\n');
docFragment.appendChild(newEle);

//add the br, or p, or something else
newEle = document.createElement('br');
docFragment.appendChild(newEle);

//make the br replace selection
var range = window.getSelection().getRangeAt(0);
range.deleteContents();
range.insertNode(docFragment);

//create a new range
range = document.createRange();
range.setStartAfter(newEle);
range.collapse(true);

//make the cursor there
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

return false;
}
}).keyup(function() {
if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
this.appendChild(document.createElement("br"));
}
})

Demo
http://jsfiddle.net/icaca/jDvau/592/