大家好,我需要将光标设置在一个没有值的文本框上的第14个位置。我知道初始时光标在0位置,但我希望它在第14个位置。
大家好,我需要将光标设置在一个没有值的文本框上的第14个位置。我知道初始时光标在0位置,但我希望它在第14个位置。
IE在设置光标位置时采用与Firefox、Opera和Chrome不同的方法。最好编写一个辅助函数,为你完成这项任务。我为自己的需求使用了这个函数。
function setCursor(node,pos){
node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node){
return false;
}else if(node.createTextRange){
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange){
node.setSelectionRange(pos,pos);
return true;
}
return false;
}
最后一步,就是从你的onfocus处理程序中调用它。
祝你好运!
window.setTimeout(function() { setCursor(node,0);}, 1);
- thomaux$("#textbox").selectionStart=14
可能适用于 Firefox、Opera 和 Chrome,但不确定是否适用于 IE。
附注:文本框中应该已经有长度大于 14 的字符才能正常工作。