我正在创建一个代码,允许我从其他地方复制文本并将其粘贴到contenteditable
中,但保留空白和断行。
这是我的代码:
// When I paste a text from another place
this.querySelector('*[contenteditable="true"]').addEventListener('paste', function(e){
// Variables
var clipboardData, pastedData;
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
// Change \n to <br>
// I use this because then I will make another things with the <br> tags
pastedData = pastedData.replace(/(?:\r\n|\r|\n)/g, '<br />');
/*
Here's a function that will get the character offset of the caret within the specified element. However, this is a naive implementation that will almost certainly have inconsistencies with line breaks. It makes no attempt to deal with text hidden via CSS (I suspect IE will correctly ignore such text while other browsers will not). To handle all this stuff properly would be tricky. I've now attempted it for my Rangy library.
*/
var caretOffset = 0;
var doc = this.ownerDocument || this.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(this);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(this);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
// Set the text at the carret position
this.innerHTML = [this.innerHTML.slice(0, caretOffset), pastedData, this.innerHTML.slice(caretOffset)].join('');
// Set the carret to the correct position
var range = document.createRange();
sel = window.getSelection();
// Try to set the range
try{
range.setStart(this.firstChild, caretOffset + pastedData.length);
} catch(err){}
// Range options
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
});
当我使用它时,它工作正常,但有时崩溃,这些是它的错误:
1)当我从.txt文件中粘贴文本时,我将插入符号放在复制文本的末尾,我尝试再次复制相同的文本。第二个文本复制在中间而不是插入符号的末尾。
2)当我在contenteditable
中有一些文本并且我用光标选择它以用另一个文本替换它时,第二个文本不会替换所选部分。它粘贴在文本的末尾,现在保留两个文本。
3)如果我正在写一个文本并按回车键来制作一个断行,在这一点上我粘贴一个文本,这将复制到前一行。
有任何解决其中一些错误的建议吗?