防止“向上箭头”键重置文本框中的光标位置

我最近在我支持的网络应用程序中添加了一些预测文本输入字段。

什么大不了吧? 不是真的,好像你的网络应用程序不这样做 – 你已经落后于时代,你的最终用户正在抱怨。 (至少这是它在这里的方式)。

所以,我的问题与“向上”箭头键有关。

预测文本框有一个onkeyup监听器。

处理程序将按键笔划分离,并根据用户输入的字符执行某些操作。

向上箭头键允许用户在我创建的加载了“建议”的div中导航。 我有几个变量跟踪索引等…基本上,当用户点击向上箭头时,我会将div的id更改为具有与之关联的css的id,这将使div看起来好像被选中一样。 此外,我将获取该div中的值并将其分配给用户可以键入的文本框。

问题是审美问题。 与我正在学习的所有文本框一样,向上箭头键将重置光标位置。 这是在我将新值写入文本字段之前发生的。

因此,在每个向上箭头笔划上,用户在文本框中看到一个跳跃光标(它将跳转到开头,并立即显示在结尾处)。

这是代码 –

 if (event.keyCode === 38 && currentUserInput.length > 0) { // user has toggled out of the text input field, save their typing thus far if (currentToggledIndex == -1) { currentToggledIndex = autoFillKeywordsList.length-1; savedKeywordUserInput = currentUserInput; } else { // revert currently selected index back to its original id document.getElementById("kw_selected").id = "kw_" + currentToggledIndex ; // user has toggled back into user input field if (currentToggledIndex == 0) { currentToggledIndex = -1; } // user has toggled to the next suggestion else { currentToggledIndex--; } } // 2. Determine next action based on the updated currentToggledIndex position // revert the user input field back to what the user had typed prior to // toggling out of the field if (currentToggledIndex == -1) { element.value = savedKeywordUserInput; } // mark the toggled index/keyword suggestion as "selected" and copy // its value into the text field else { document.getElementById("kw_"+currentToggledIndex).id = "kw_selected"; element.value = autoFillKeywordsList[currentToggledIndex]; } // 3. Determine what the user can do based on the current value currently // selected/displayed displayAppropriateButtonActions(element.value); } 

有趣的是 – “向下”箭头完美地工作,因为默认情况下,向下箭头键将光标放在当前位于文本框中的字符串的末尾。

好的,我已经尝试过的东西 –

event.preventDefault(); event.stopPropogation();

我还尝试使用我在另一篇文章中找到的setCursorPosition函数将光标位置PRIOR设置为无效。 (是的,我正在接触这个)

我将其标记为JavaScript和Jquery。 我更喜欢使用JavaScript,但也欢迎使用Jquery中的建议!

我认为你可以做的是当他们移动光标时,抓住它并找出它是什么元素……然后将它存储在变量中并聚焦()它并擦除它然后将你存储的值放回去。

 var holdme = $("#myelement").val(); $("#myelement").focus().val('').val(holdme); 

当大多数时候在jquery / javascript中出现奇怪的游标问题时,这对我有用。 试一试,如果它不起作用,请告诉我,我会看到还有什么可能是错的。

正如瑞安建议的那样。 我是如何在角度4.x中实现这一点的

html的

 <.. (keydown)="keyDownEvent($event)" > 

.TS

 keyDownEvent(event: any){ if (event.keyCode === 38 && event.key == "ArrowUp") { event.preventDefault(); //logic.. }