如何在阻止浏览器的默认粘贴操作时固定光标位置

How to fix cursor position when prevent browser's default paste action

有一种自定义方法可以将 HTML(html 片段不仅仅是纯文本 ) 插入到编辑器(富文本编辑器)中,但是对于出于某种原因,我必须使用 e.preventDefault 来防止浏览器默认粘贴操作并稍后插入复制数据。我的代码如下所示:

editor.addEventListener('paste', function(e) {
   var data = e.clipboardData.getData('text/html'),
       newData;
   e.preventDefault();
   newData = custom.handle(data);
   custom.insert(newData);
}, false); 

custom.insert(newData)之后,光标还在原点闪烁。我预计它会移动 newData.

的末尾

谁能帮我解决这个问题?

您的问题可能已经在这里有了答案:

Use JavaScript to place cursor at end of text in text input element

Set focus and cursor to end of text input field / string w. Jquery

对于 Mike Berrow 的示例,您可以将输入值替换为自身以将插入符设置为输入的末尾。这似乎是最可靠的方法,如果它有点 hackish。

myInput.value = myInput.value;

对于支持它的浏览器,您可以使用 setSelectionRange 方法。由于您已经使用了 clipboardData,所以这应该不是问题。

myInput.setSelectionRange(myInput.value.length, myInput.value.length);

请注意,如果您使用的是文本区域,则值长度可能更难获得。

https://developer.mozilla.org/fr/docs/Web/API/HTMLInputElement/setSelectionRange

我不知道你的 custom 函数的属性是什么,但是你可以使用这段代码将光标移动到 input 和 [=15] 中文本的末尾=]:

custom.selectionStart = custom.selectionEnd;

如果 newData 粘贴在文本的中间或开头,那么您将必须计算 newData 的长度并将光标移动那么多字符。类似于:

custom.selectionStart = custom.selectionStart + newData.length;
custom.selectionEnd = custom.selectionStart;

编辑以回答您的问题: 如何使用 HTML 标签计算文本的长度?

好吧,这会有点棘手。可以在内存中创建一个临时的HTML元素,在其中添加newData,计算其innerText属性的长度。像这样:

var temp = document.createElement("div");
temp.innerHTML = newData;
custom.selectionStart = custom.selectionStart + temp.innerText.length;
custom.selectionEnd = custom.selectionStart;

注意:innerText 是由 Microsoft 引入的,不是 W3C 标准。尽管大多数浏览器复制了 IE 的行为,但实现因浏览器而异。 innerText 是样式感知的,只会 return 可见文本。