游標聚焦的位置在最前面
複製代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jquery聚焦文字框 -指令碼之家</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form action="http://www.baidu.com" id="cse-search-box">
<div>
<input type="hidden" name="cx" value="partner-pub-7740261255677392:7064996710" />
<input type="hidden" name="ie" value="UTF-8" />
<!--文字框--><input type="text" name="q" size="25" />
<input type="submit" name="sa" value="搜索" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("input[name='q']").focus();
})</script>
</body>
</html>
jquery擴充文字框聚焦方法
在不同的瀏覽器中,一個文字框,如果只是直接給文字框設定focus(),那麼游標聚焦的位置可能是在最前面。下面的代碼則是給jquery擴充一個textFocus方法,用於聚焦文字框,並使游標在最後,使用$("input").textFocus()。也可以傳入一個數字參數,設定游標聚焦的位置。如$("input").textFocus(2),則游標在在第二個字元後面。
複製代碼 代碼如下:
(function($){
$.fn.textFocus=function(v){
var range,len,v=v===undefined?0:parseInt(v);
this.each(function(){
if($.browser.msie){
range=this.createTextRange(); //文字框建立範圍
v===0?range.collapse(false):range.move("character",v); //範圍摺疊
range.select(); //選中
}else{
len=this.value.length;
v===0?this.setSelectionRange(len,len):this.setSelectionRange(v,v); //dom直接設定選區,然後focus
}
this.focus();
});
return this;
}
})(jQuery)