【发布时间】:2016-06-09 17:38:37
【问题描述】:
使用下面的代码,我可以在contenteditable div 中成功输入文本,而不是在按下回车按钮时创建新的div,而是创建<br>。
如何在contentedtiable div 内的文本周围添加<p> 标签?
$('button').click(function() {
$('pre').text($('div')[0].outerHTML)
});
$('div[contenteditable=true]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode == 13) {
// insert 2 br tags (if only one br tag is inserted the cursor won't go to the second line)
document.execCommand('insertHTML', false, '<br><br>');
// prevent the default behaviour of return key pressed
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 50px; border: 1px solid;" contenteditable="true"></div>
<pre></pre>
<button>Show Source</button>
我想要的上述脚本的输出如下:
<div contenteditable="true">
<p>
// content here
</p>
</div>
注意:我不希望在单击按钮时添加 <p> 标签,而是自动添加。
JsFiddle:https://jsfiddle.net/r3qthx6d/5/
更新
当在contenteditable div 中输入内容时,使用$('div[contenteditable=true]').wrapInner('<p></p>'); 在文本末尾添加<p> 标签,如下所示:https://jsfiddle.net/r3qthx6d/3/
但这不是我需要的,因为我的目标是让内容被<p>标签包围。
【问题讨论】:
标签: jquery html contenteditable