且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试将空跨度添加到contenteditable div时左右按钮行为异常

更新时间:2022-01-29 23:01:20

我找出了问题,并修复了左右错误,这是更新的小提琴

I figured out the problem and I fixed the missbehaving left and right, here is the updated fiddle http://jsfiddle.net/2PS3m/5/ with the fixes included.

发生了什么事

在setAutoCompletePos()函数中,您实际上是在完全替换_result元素的内容(_result.html(text);),这使它失去了选择,并在开始时就跳转了

In your setAutoCompletePos() function you were essentially replacing the content of your _result element completely ( _result.html(text); ) which made it lose its selection and was jumping at the beginning

看似键的行为不正确,实际上是丢失了原始文本+选择/插入符的位置

What seemingly was a misbehaving keys, was actually loss of original text + selection/ caret position

解决方案是在更改元素的内容之后执行restoreSelection(),这实际上将插入符号的位置设置为原来的位置.

the solution to that was to do restoreSelection() after you changed the contents of your element, which essentially sets back the caret to where it was.

我还将keydown更改为keyup,并向元素添加了mouseup事件,以便在任何事情发生之前保存初始选择.

I also changed the keydown to keyup and added a mouseup event to the element in order to save the initial selection before anything happens.

对于这样的操作,***使用keyup事件而不是keydown来允许插入符号在执行所需的操作之前更改位置.

For operations like this is best to use keyup event instead of keydown to allow the caret to change position before you do the operations you need.

mouseup事件本质上用于捕获用户在文本中的点击,并将插入号的初始位置存储在我在您的代码中添加的变量中.

The mouseup event is used essentially to capture the user's click within the text and stores the initial position of the caret in a variable that I added in your code.

因此您的setAutoCompletePos函数变得像这样,并按预期工作:

so your setAutoCompletePos function became like this and works as expected:

function setAutoCompletePos() {
    var offsetPos;
    _result.remove('.spanPos');
    var text = _fullText.slice(0, _caretPos) + _spanElem + _fullText.slice(_caretPos);
    _result.html(text);
    restoreSelection(_result.get(0), _savedSel); //added this
    offsetPos = $('.spanPos').offset();
}

从修改的提琴中获取代码 http://jsfiddle.net/2PS3m/5/ 尝试一下,并告诉我它是否对您有用,我对其进行了测试,结果表明它可以按预期运行,而不会在开始时出现光标跳动.

Get the code from the modified fiddle http://jsfiddle.net/2PS3m/5/ try it and tell me if it works for you, my tests on it, show that it works as expected without cursor jumping at the beginning.