When the user edits a contenteditable div
, and press some keys, I would like to override the default behavior.
For instance, I want to insert a normal line break when the user press ENTER.
I do that using document.execCommand("insertText",...)
This is the only way I have found so far to make this action undoable and redoable by the user.
<div id="editor" contenteditable="true" style="white-space:pre-wrap">
Some text....
</div>
<script>
$("#editor").keydown(function(evt){
console.log(evt.keyCode);
if(evt.keyCode==13){
document.execCommand("insertText",false,"
");
evt.preventDefault();
evt.stopPropagation();
}
}
</script>
This code works well on chrome and firefox. But, ie does not support "inserttext". Would there be a way to insert text with ie, such that the user can undo it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…