gpt4 book ai didi

javascript - 防止 "up arrow"键重置文本框内的光标位置

转载 作者:数据小太阳 更新时间:2023-10-29 05:36:07 25 4
gpt4 key购买 nike

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

很重要,对吧?不尽然,如果您的网络应用程序不这样做——您已经落伍了,您的最终用户正在提示。 (至少这里是这样的)。

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

预测文本框有一个 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();

我还尝试使用我在另一篇文章 here 上找到的 setCursorPosition 函数在将新值设置为无效之前设置光标位置. (是的,我正在接触这个)

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

最佳答案

正如 Ryan 所建议的那样。我是如何在 Angular 4.x 中实现这一点的

.html

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

.ts

keyDownEvent(event: any){

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

关于javascript - 防止 "up arrow"键重置文本框内的光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com