我正在为我的一个项目制作一个简单的编辑器,我需要使用可编辑的 div 使用contenteditable
财产。我需要两个功能:
- 输入两次后自动插入小时
- 创建一个段落而不是
<br>
进入并专注于它。
所以我写了这个(带着一些灵感),这是负责的代码的一部分:
var intercept = {
keydown: function(e)
{
if( e.which == 13 ){
intercept.enterKey.call(null, e);
}
},
enterKey: function(e)
{
var $lastElm;
// Find the previous elm
if (document.selection) { // IE
$lastElm = $(document.selection.createRange().parentElement());
} else { // everyone else
$lastElm = $(window.getSelection().anchorNode);
}
// Handle enter key
if( !e.shiftKey )
{
// Check if two or more paragraphs
// are empty, so we can add an hr
if(
$.trim($lastElm.text()) === "" &&
!$lastElm.prev().is('hr')
){
document.execCommand('insertParagraph', false);
$lastElm.replaceWith($('<hr>', {contenteditable: false}));
}
// Or just add an paragraph
else{
document.execCommand('insertParagraph', false, true);
}
e.preventDefault();
}
}
}
这在 Chrome 中工作正常,但在 Firefox 中,它不会创建新的<p>
元素,我认为它只是将当前文本包装在p
这是不可能的,因为它已经在p
。所以光标只是停留在 Firefox 中并且不会创建新段落。
您知道如何解决这个问题吗?
Thanks.
From Jquery you can use this method:
var html="";
var intercept = {
keydown: function(e)
{
if( e.which == 13 ){
intercept.enterKey.call(null, e);
}
},
enterKey: function(e)
{
$("#append_id").html("");
html+="your text";
$("#append_id").html("<p>"+html+"</p>");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)