代码例子:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8">
<title>contenteditable,Ctrl+Enter换行,Enter发送</title>
<meta name="description" content="">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="author" content="">
<style type="text/css">
#msgList,
#editor,
#error {
width: 500px;
margin: auto;
padding: 10px;
}
#msgList {
min-height: 100px;
}
#editor {
border: 1px solid #CCC;
background: #F5F5F5;
overflow: auto;
line-height: 22px;
height: 80px;
outline-style: none;
font-size: 14px;
}
#error {
color: #F30;
font-size: 12px;
padding: 0;
line-height: 25px;
}
.msg-item {
border: 1px solid #EEE;
background: #FEFEFE;
margin: 10px 0;
padding: 10px;
font-size: 12px;
}
</style>
</head>
<body>
<div id="msgList"></div>
<div id="editor" contenteditable="true" style="color:#CCC;">在这里输入,按Enter发出。<br>Ctrl+Enter换行。</div>
<div id="error"></div>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script>
// debugger
$(function() {
$('#editor').on('focus', function() {
var $this = $(this);
if ($this.html().replace(/\s/g, '') == '在这里输入,按Enter发出。<br>Ctrl+Enter换行。') {
$this.html('').css('color', '#333');
}
})
$('#editor').on('blur', function() {
var $this = $(this);
if ($this.html().replace(/\s/g, '') == '') {
$this.html('在这里输入,按Enter发出。<br>Ctrl+Enter换行。').css('color', '#CCC');
}
})
document.onkeydown = function(e) {
var $editor = $('#editor');
//编辑框聚焦下才触发事件
// if($editor.is(':focus')){
// 判断输入框是否获得焦点
if (document.activeElement.id == 'editor') {
var inputText = $('#editor').html();
if (!e) e = window.event;
//按ctrl+enter换行
if (e.ctrlKey && e.which == 13) {
$editor.append('<div><br/></div>')
placeCaretAtEnd($editor.get(0));
$editor.animate({
scrollTop: 10000
}, 100)
return false;
}
//按enter发送
if ((e.keyCode || e.which) == 13 && !e.ctrlKey) {
if (inputText == '') {
$('#error').html('请输入内容');
return false;
}
$('#error').html('');
var str = '<div class="msg-item">' +
'<div class="msg-content">' + inputText + '</div>' +
'</div>'
$('#msgList').append(str);
$editor.html('');
$('#msgList').animate({
scrollTop: 100000
}, 200);
return false;
}
}
}
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" &&
typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
})
</script>
</body>
</html>