首页 > 解决方案 > 当 onPaste 在 contenteditable div 内时,新行将变成空 div,例如

, 代替

问题描述

我正在研究 contenteditable div,这似乎是一个完整的噩梦。

我的问题是:

我正在拦截粘贴事件,因为我应该只允许纯文本/文本。

任何空行都应显示为:<div><br></div>,但是当您复制多行并将其粘贴到 contenteditable 周围时,div您会在控制台中看到一些空行被呈现为空 div 之类的<div></div>。(请全屏查看下面的测试片段以查看控制台)。请参阅下面的图片。

我想这与换行符有关。

我怎样才能防止这种情况发生并确保如果一行是空的,它会变成:

<div><br></div>?

注意:我没有使用 jQuery。

在此处输入图像描述

在此处输入图像描述

测试片段

function handleInput() {
  console.log('DIV innerHTML: ');
  console.log(document.getElementById('root').innerHTML);
 }
 
function handlePaste(e) {
  e.preventDefault();
  // GET TEXT REPRESENTATION OF CLIBOARD DATA
  let text = (e.originalEvent || e).clipboardData.getData('text/plain');
  console.log('THIS IS BEING PASTEEEEEEEEEEEEEEEED! ' + text);
  text = text.replace('\r\n','\n');
  text = text.replace('\r','\n');
  // INSERT TEXT MANUALLY
  document.execCommand("insertText", false, text);
}
#root {
  border: 1px dotted blue;
}
<p>Copy and paste multiple lines including empty ones</p>
<div id="root" contenteditable oninput="handleInput()" onpaste="handlePaste(event)">
  <div>123</div>
  <div><br></div>
  <div><br></div>
  <div>123</div>
</div>

标签: javascripthtml

解决方案


问题实际上与我尝试替换\rand\n字符的方式有关。我还需要将它替换为两个\n,以便每个换行符<br>在 contenteditable 中接收一个div

这是我解决它的方法:

function onPaste(e) {
    e.preventDefault();
    // GET TEXT REPRESENTATION OF CLIBOARD DATA
    let text = (e.originalEvent || e).clipboardData.getData('text/plain');
    console.log('Text before replace:');
    console.log(text);
    console.log(text.split('\n'));
    text.split('\n').forEach((item)=>console.log(JSON.stringify(item)));

    text = text.replace(/(?:\\[rn]|[\r\n]+)+/g,'\n\n');


    console.log('Text after replace:');
    console.log(text);
    console.log(text.split('\n'));
    text.split('\n').forEach((item)=>console.log(JSON.stringify(item)));

    // INSERT TEXT MANUALLY
    document.execCommand("insertText", false, text);
  }

带有工作解决方案的片段

function handleInput() {
  console.log('DIV innerHTML: ');
  console.log(document.getElementById('root').innerHTML);
 }
 
function handlePaste(e) {
  e.preventDefault();
  // GET TEXT REPRESENTATION OF CLIBOARD DATA
  let text = (e.originalEvent || e).clipboardData.getData('text/plain');
  
  text = text.replace(/(?:\\[rn]|[\r\n]+)+/g,'\n\n');
  
  // INSERT TEXT MANUALLY
  document.execCommand("insertText", false, text);
}
#root {
  border: 1px dotted blue;
}
<p>Copy and paste multiple lines including empty ones</p>
<div id="root" contenteditable oninput="handleInput()" onpaste="handlePaste(event)">
  <div>123</div>
  <div><br></div>
  <div><br></div>
  <div>123</div>
</div>


推荐阅读