DIV CSS 佈局教程網

jQuery 聚焦文本框:默認光標定位與自定義 textFocus 擴展
編輯:JQuery特效代碼     

搜索框打開頁面就自動獲得焦點,是提升用戶體驗的小細節。用 jQuery 實現只需一行,但真正麻煩的是光標插入點的位置——不同瀏覽器對 focus() 的處理並不一致,光標往往停在文本最前面,而不是我們期望的末尾。

基礎做法:讓文本框自動獲焦

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jquery聚焦文本框</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form action="https://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>

進階:擴展 textFocus 方法

為了解決光標位置的問題,可以給 jQuery 原型掛一個自定義方法 textFocus()。它支持傳入數字參數來指定插入點,不傳則默認把光標放到文本末尾。

(function($) {
    $.fn.textFocus = function(v) {
        var range, len, v = v === undefined ? 0 : parseInt(v);
        this.each(function() {
            if ($.browser.msie) {
                range = this.createTextRange();          // IE 下創建文本範圍
                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);
            }
            this.focus();
        });
        return this;
    };
})(jQuery);

調用方式

$("input").textFocus();     // 光標定位到文本末尾
$("input").textFocus(2);    // 光標定位到第二個字符之後

實現思路說明

核心邏輯分兩支:

  • IE 分支:調用元素自身的 createTextRange() 拿到文本範圍對象,再用 collapse(false) 折疊到末尾,或用 move("character", v) 向前移動指定字符數,最後 select() 選中。
  • 標準分支:直接用 DOM 提供的 setSelectionRange(start, end),兩個參數相同即為光標定位而非選中文本。

注意函數返回 this,保留了 jQuery 的鏈式調用特性,這是寫插件時值得堅持的習慣。另外,IE 分支依賴的 $.browser 在 jQuery 1.9 之後已被移除,新項目建議改用特性檢測(例如判斷 document.selection 是否存在)來替代。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved