我正在尝试构建一个与 Google 搜索页面以及 Gmail 和其他几个页面(包括此页面 - 请参阅“提问”页面上的“标签”输入)类似的工作方式的表单。输入文本时,将出现一个选项列表,用户可以使用向上和向下箭头来选择他们想要的选项。
我遇到的问题是向上箭头将光标/插入符号放在字段的位置 0 处,向下箭头将其放在末尾。有没有一种简单的方法可以防止它移动到开头/结尾,或者我是否需要在函数运行之前找到插入符位置,并在运行之后将其重新定位到该位置?
这是在输入元素 (onkeyup) 中输入文本时运行的函数的开头。
var keycode = checkKeycode (event); // returns the keycode of the key pressed.
if (keycode == 38) { // up arrow
var selection = $(".optionsSelected").attr("id");
var selId = parseInt(selection.replace('briefOption', ''));
if (selId != 0) {
$(".optionsSelected").removeClass("optionsSelected");
var newSelId = selId - 1;
$("#briefOption"+newSelId).addClass("optionsSelected");
}
}
else if (keycode == 40) { // down arrow
var selection = $(".optionsSelected").attr("id");
var selId = parseInt(selection.replace('briefOption', ''));
if (selId != numAvEmps && numAvEmps != 0) {
$(".optionsSelected").removeClass("optionsSelected");
var newSelId = selId + 1;
$("#briefOption"+newSelId).addClass("optionsSelected");
}
}
else if (keycode == 27) { // Escape
$("#docDropDown").css("display","none");
}
else if (keycode == 9 || keycode == 13) { //tab or enter
/* Fill form */
}
如果有更多代码有用,请告诉我。感谢您的帮助。
最佳答案
您需要先存储插入符号,然后在完成操作后将其放回去。
类似这样的事情:
HTML 正文:
<input type="text" id="mytextbox" style="border: 1px solid black" />
Javascript:
function getCaretPosition(ctrl)
{
var caretPos = 0;
// IE
if (document.selection)
{
ctrl.focus ();
var sel = document.selection.createRange();
sel.moveStart ('character', -ctrl.value.length);
caretPos = sel.text.length;
}
// Firefox
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
{
caretPos = ctrl.selectionStart;
}
return caretPos;
}
function setCaretPosition(ctrl, pos)
{
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange)
{
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
$(document).ready(function ()
{
$("#mytextbox").keydown(function (e)
{
// Up
if(e.which == 38)
{
var pos = getCaretPosition(this);
// Do stuff here that changes the value/caret?
setCaretPosition(this, pos);
}
// Down
else if(e.which == 40)
{
var pos = getCaretPosition(this);
// Do stuff here that changes the value/caret?
setCaretPosition(this, pos);
}
});
});
关于javascript - 如何防止光标/插入符号在输入文本元素内移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3419426/