当onPaste里面有令人满意的div时,新线就变成了空的div , instead of

问题描述 投票:0回答:1

我正在研究一个令人满意的div,这似乎是一个完整的噩梦作为一个想法。

我的问题是:

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

任何空行都应该显示为:<div><br></div>,但是当你复制多行并将其粘贴到满足的div时,你会在控制台中看到一些空行被渲染为像<div></div>这样的空div。 (请参阅下面的全屏测试片段以查看控制台)。见下图。

我想这与断线字符有关。

如何防止这种情况发生,并确保如果一行为空,它将变为:

<div><br></div>

注意:我没有使用jQuery。

enter image description here

enter image description here

测试片段

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>
javascript html
1个回答
0
投票

这个问题与我试图取代\r\n字符的方式有关。我还需要为两个\n替换它,以便每个换行符在满足的<br>中获得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);
  }

SNIPPET与工作解决方案

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>
© www.soinside.com 2019 - 2024. All rights reserved.