- JScript code
$('#month').blur(function() { var va = $("#month").attr("value"); if (va != "" && !/^\d+(.\d{1,2})?$/.test(va)) { window.alert('月份输入错误!'); $("#month").focus(function(){ $("#month").val($("#month").val()); }); $("#month").focus(); return false; } });
上边的代码有问题
1.如果不谈出错误提示,代码没有问题,光标可以一直停留在右侧
2.弹出错误提示后,焦点是可以停留在文本框的右边的
3.问题在这,弹出错误提示后,光标停留在文本框文字的右侧,然后删除掉错误字符,光标离开,再将光标给文本框,这个时候焦点就自动跑到文本框最左侧去了
改了半天,改不成功了
------解决方案--------------------
你开始怎么让光标在右边的?在函数中在用一下白
------解决方案--------------------
http://jsbin.com/icigul/edit#html,live
- HTML code
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <meta name="author" content="http://weibo.com/zswang" /> <title>Demo 示例控制输入光标位置</title> <style> </style> </head> <body> <input id="editor" type="text" value="1234" /> <input id="left" type="button" value="left" > <input id="right" type="button" value="right" > <script> void function(){ function setSelection(editor, pos){ if (editor.setSelectionRange){ editor.focus(); editor.setSelectionRange(pos, pos); } else if (editor.createTextRange){ var textRange = editor.createTextRange(); textRange.collapse(true); textRange.moveEnd("character", pos); textRange.moveStart("character", pos); textRange.select(); } } var editor = document.getElementById('editor'); document.getElementById('left').onclick = function(){ setSelection(editor, 0); } document.getElementById('right').onclick = function(){ setSelection(editor, editor.value.length); } }(); </script> </body> </html>