gpt4 book ai didi

javascript - 如何在 contenteditable div 中创建一个段落?

转载 作者:搜寻专家 更新时间:2023-11-01 04:43:25 28 4
gpt4 key购买 nike

我正在为我的项目制作一个简单的编辑器,我需要使用 contenteditable 来使用可编辑的 div属性(property)。我需要两个功能:

  • 两次输入后自动插入小时
  • 创建一个段落而不是 <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 中,不会创建新段落。

你知道如何解决这个问题吗?
谢谢。

最佳答案

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>");
}
}

关于javascript - 如何在 contenteditable div 中创建一个段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18814094/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com