如何在contenteditable div中创建一个段落?
我正在为我的一个项目编写一个简单的编辑器,我需要使用一个可编辑的div使用contenteditable
属性。 我需要两个function:
- 两次进入后自动插入hr
- 在输入时创建一个段落而不是
,并专注于它。
所以我写了这个(有一些灵感),这是负责的代码的一部分:
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($('
', {contenteditable: false})); } // Or just add an paragraph else{ document.execCommand('insertParagraph', false, true); } e.preventDefault(); } } }
这在Chrome中运行良好,但在Firefox中,它不会创建一个新的
元素,我认为它只是将当前文本包装在p
,这是不可能的,因为它已经在p
。 所以光标只停留在Firefox中,并且没有创建新的段落。
你知道如何解决这个问题吗?
谢谢。
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(""+html+"
"); } }
我做了一些完全基于JQuery的东西:
var debug=0; $(function (){ $(".test").on('blur keyup paste focus focusout',function (){ if($(".test").children().size()==0) { if(debug) console.log("add p"); //Only Test now var text=$(".test").text(); $(".test").empty(); $(".test").append(""+text+"
"); } if(debug) console.log("-------------------------"); if(debug) console.log($(".test").children()); for(var i=0;i<$(".test").children().size();i++) { var tag=$(".test").children().eq(i).prop("tagName").toLowerCase(); console.log("i="+i+" ["+tag+"]"); if(i%3==2) { if($(".test").children().size()==i+1 && $(".test").children().last().text()=="") continue; if(tag!="hr") { if(debug) console.log(" add hr"); $(".test").children().eq(i).before("
") } } else if(tag=="hr") { if(debug) console.log(" rm hr"); $(".test").children().get(i).remove(); } else if(tag=="br") { if(debug) console.log(" br"); $(".test").children().eq(i).remove(); var text=$(".test").children().size>=i?$(".test").children().eq(i+1).text():""; $(".test").children().eq(i).after($(""+text +"
")); $(".test").children().eq(i).append(""+text+"
"); if($(".test").children().size>=i+1) $(".test").children().eq(i+1).remove(); } else if (tag!="p") { if(debug) console.log(" not p"); var text=$(".test").children().eq(i).text(); $(".test").children().eq(i).remove(); $(".test").children().eq(i).after($(""+text +"
")); } } });
希望这可以帮助!