Sal*_*lar 5 javascript jquery contenteditable
我正在为我的一个项目编写一个简单的编辑器,我需要使用一个可编辑的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这在Chrome中运行良好,但在Firefox中,它不会创建一个新<p>元素,我认为它只是将当前文本包装在一个p不可能的文本中,因为它已经存在了p.所以光标只停留在Firefox中,并且没有创建新的段落.
你知道如何解决这个问题吗?
谢谢.
小智 -1
我做了一些完全基于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("<p>"+text+"</p>");
}
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("<hr/>")
}
}
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($("<p>"+text +"</p>"));
$(".test").children().eq(i).append("<p>"+text+"</p>");
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($("<p>"+text +"</p>"));
}
}
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
1994 次 |
| 最近记录: |