jquery聚焦文字框與擴充文字框聚焦方法

來源:互聯網
上載者:User

游標聚焦的位置在最前面
複製代碼 代碼如下:
<!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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.