iva*_*ago 6 javascript jquery textbox arrow-keys onkeyup
我最近在我支持的网络应用程序中添加了一些预测文本输入字段.
大不了吧?不是真的,好像你的网络应用程序不这样做 - 你已经落后于时代,你的最终用户正在抱怨.(至少这是它在这里的方式).
所以,我的问题与"向上"箭头键有关.
预测文本框有一个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);
}
Run Code Online (Sandbox Code Playgroud)
有趣的是 - "向下"箭头完美地工作,因为默认情况下,向下箭头键将光标放在当前位于文本框中的字符串的末尾.
好的,我已经尝试过的东西 -
event.preventDefault();
event.stopPropogation();
我也试图设置之前,使用一个setCursorPosition功能我在另一篇文章中找到新的值设置为无果光标位置在这里.(是的,我正在接触这个)
我将其标记为JavaScript和Jquery.我更喜欢使用JavaScript,但也欢迎使用Jquery中的建议!
我认为你可以做的是,当他们移动光标时,抓住它并找出它是什么元素......然后将其存储在变量中并 focus() 它并删除它,然后将存储的值放回其中。
var holdme = $("#myelement").val();
$("#myelement").focus().val('').val(holdme);
Run Code Online (Sandbox Code Playgroud)
当我大多数时候在 jquery/javascript 中遇到奇怪的光标问题时,这对我有用。尝试一下,如果不起作用,请告诉我,我会看看还有什么问题。