javascript - 当 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>
解决方案
问题实际上与我尝试替换\r
and\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>
推荐阅读
- php - PHP For循环中的每7个和8个表格单元格样式
- java - 即使使用 table.setRowSelectionAllowed(true) 添加颜色后也无法选择 jtable 行
- c# - ManualResetEvent 在 Mono 中无法按预期工作
- ruby - ruby gsub 和 preg_replace 中的排序替换
- javascript - 如何在不进行任何 API 调用的情况下获取浏览器 IP 地址和访问我网站的访问者国家/地区
- android - 在 Android Studio 版本 3.1.3 上测量我的应用性能
- ibm-cloud - 为什么我在 Watson IoT Platform 上的历史数据库服务不断变得“未配置”?
- chef-infra - chef-server-ctl 重新配置失败
- java - nexus/maven 部署到 nexus 服务器的旧 IP
- ios - 收到推送通知时运行代码。即使应用程序在后台