如何使内容可编辑的div的行为像一个文本区域? [英] How to make a content editable div behave like a text area?
问题描述
我已经建立了一个编辑器,可将markdown转换为html。现在,我必须使用 jquery autosize 插件来调整文本区域的大小。
I have built an editor that converts markdown to html. Right now I have to use jquery autosize plugin to resize the text area as it grows.
如果我使用内容可编辑的div,我可以绕过它。但内容可编辑div的问题是它不保留新行。每次按下返回键时都会插入一个新的div。这打破了markdown到html为我的应用程序的渲染。
If I use a content-editable div I can bypass it. But the problem with content editable div is that it does not preserve new lines. It inserts a new div every time return key is pressed. This breaks the rendering of markdown to html for my application.
有没有什么办法,我可以使一个内容可编辑的div的行为完全像文本区域?
Is there any way I can make a content editable div behave exactly like text area?
推荐答案
编辑
在@Mr_Green注释之后,请查看 Make a< br>而不是< div>< / div>
Edit
After the @Mr_Green comment above, you should have a look at Make a <br> instead of <div></div> by pressing Enter on a contenteditable
正确的JS代码是:
$(function(){
$("#editable")
// make sure br is always the lastChild of contenteditable
.live("keyup mouseup", function(){
if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
this.appendChild(document.createChild("br"));
}
})
// use br instead of div div
.live("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
}
});
})
;
您可以拦截 Enter
按键,并将其替换为< br> ;
with Javascript:
You can intercept the Enter
key press and replace it with a <br>
with Javascript :
$(function(){
$("#editable").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
if (document.selection) {
document.selection.createRange().pasteHTML("<br/>");
} else {
$(this).append("<br/>");
}
}
});
});
这篇关于如何使内容可编辑的div的行为像一个文本区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!