【问题标题】:how to get multiline html of a contenteditable div如何获取内容可编辑 div 的多行 html
【发布时间】:2021-03-09 18:25:27
【问题描述】:

写在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>

【问题讨论】:

  • FYI 这在 Firefox 中有效,段落包裹在第一行
  • @Dominik,谢谢,不幸的是我在 Chrome 上
  • @qadenza 只是关于 div 的第一行?因为它在第一行之后效果很好。
  • @oguzhancerit - 否 - 尝试使用 lorem ipsum dolor - 结果中加入了每一行,没有任何行尾
  • @qadenza 我得到了。也许你可以看这里:stackoverflow.com/questions/12592254/…

标签: javascript html jquery contenteditable


【解决方案1】:

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

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>

【讨论】:

  • 请尝试 - 这根本不是我想要的结果
  • @qadenza 我试过了。目前尚不清楚您的期望。请澄清。
  • 请阅读我的问题 - how to get this:...在你的解决方案中,我得到了这个 - [ "loremipsum" ]
  • 你试过你的sn-p了吗?我收到了 - [ "loremipsum" ]
  • @qadenza 答案已更新。您只需要为新行添加 JavaScript 转义码 \n
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 2013-10-03
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
相关资源
最近更新 更多