如何获得内容可编辑的 div 的多行 html

how to get multiline html of a contenteditable div

把这个写在里面ed

lorem  
ipsum

然后点击按钮。结果:

lorem<p>ipsum</p>

如何获得:

<p>lorem</p>
<p>ipsum</p>

我在 Chrome,最新版本

document.execCommand("defaultParagraphSeparator", false, "p");

$('button').on('click', () => {
    let a = $('#ed').html();
    $('#btex').val(a);
    console.log(a);
});
.ed{
min-height:25px;
background:gold;
outline:none;
}
.btex{
display:block;
width:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<br><br>
<div class='ed' id='ed' contenteditable autofocus></div>
<br>
<textarea class='btex' id='btex'></textarea>

您可以在 space 拆分输入,然后遍历生成的数组元素,用段落包装每个元素。

document.execCommand("defaultParagraphSeparator", false, "p");

$('button').on('click', () => {
    // Split the text of the div where there are spaces
    // and return the parts in an array
    let a = $('#ed').html().replace("</p>", "").split("<p>");
    
    // Loop through the array and add each item (wrapped in <p></p>) to a new array
    // Then, join that resulting array's elements with nothing to create a string.
    $('#btex').val(a.map(function(item){ return "<p>" + item + "</p>" }).join("\n"));
});
.ed{
min-height:25px;
background:gold;
outline:none;
}
.btex{
display:block;
width:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<br><br>
<div class='ed' id='ed' contenteditable autofocus></div>
<br>
<textarea class='btex' id='btex'></textarea>