2010-12-02 139 views
70

如何在頁面加載時將光標聚焦在特定的輸入框中?加載焦點輸入框

是否可以保留初始文本值以及將光標置於輸入的結尾?

<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" /> 

回答

130

有兩個部分給你的問題。

1)如何在頁面加載時關注輸入?

您可以將autofocus屬性添加到輸入中。

<input id="myinputbox" type="text" autofocus> 

但是,這可能不被所有瀏覽器支持,所以我們可以使用javascript。

window.onload = function() { 
    var input = document.getElementById("myinputbox").focus(); 
} 

2)如何放置光標在輸入文本的結尾?

下面是一個非jQuery解決方案,其中有一些來自another SO answer的借來的代碼。

function placeCursorAtEnd() { 
    if (this.setSelectionRange) { 
    // Double the length because Opera is inconsistent about 
    // whether a carriage return is one character or two. 
    var len = this.value.length * 2; 
    this.setSelectionRange(len, len); 
    } else { 
    // This might work for browsers without setSelectionRange support. 
    this.value = this.value; 
    } 

    if (this.nodeName === "TEXTAREA") { 
    // This will scroll a textarea to the bottom if needed 
    this.scrollTop = 999999; 
    } 
}; 

window.onload = function() { 
    var input = document.getElementById("myinputbox"); 

    if (obj.addEventListener) { 
    obj.addEventListener("focus", placeCursorAtEnd, false); 
    } else if (obj.attachEvent) { 
    obj.attachEvent('onfocus', placeCursorAtEnd); 
    } 

    input.focus(); 
} 

下面是我如何用jQuery完成此任務的示例。

<input type="text" autofocus> 

<script> 
$(function() { 
    $("[autofocus]").on("focus", function() { 
    if (this.setSelectionRange) { 
     var len = this.value.length * 2; 
     this.setSelectionRange(len, len); 
    } else { 
     this.value = this.value; 
    } 
    this.scrollTop = 999999; 
    }).focus(); 
}); 
</script> 
+2

第一個代碼塊實際上是建議PLA在現有值的末尾也顯示光標,它的效果很好。我讚賞你的幫助。 – Codex73 2010-12-02 12:47:26

3

代碼片段:

 

function focusOnMyInputBox(){ 
    document.getElementById("myinputbox").focus(); 
} 

<body onLoad="focusOnMyInputBox()")> 


<input type="text" size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text" /> 
 
2

這樣做的一個可移植的方法是使用自定義函數(處理瀏覽器的差異),如this one

然後設置爲onload<body>標籤的末端處理程序,如jessegavin寫道:

window.onload = function() { 
    document.getElementById("myinputbox").focus(); 
} 
40

剛擡起頭 - 你可以用HTML5來支持它的瀏覽器現在做到這一點沒有JavaScript:

<input type="text" autofocus> 

您可能想從此開始並使用JavaScript構建它,以便爲舊版瀏覽器提供回退。

+0

很高興知道,這是否已經將光標移動到輸入字段中的最後一個位置? – 2010-12-02 02:18:06

+1

我不認爲@ Codex73正試圖完成HTML5中的佔位符屬性。這聽起來像他希望光標自動定位在當前輸入中的任何值的末尾。 – jessegavin 2010-12-02 02:24:39

9
$(document).ready(function() { 
    $('#id').focus(); 
}); 
1

如果您不能添加到出於某種原因,BODY標籤,您可以將表格後補充一點:

<SCRIPT type="text/javascript"> 
    document.yourFormName.yourFieldName.focus(); 
</SCRIPT> 
1

做工精細...

window.onload = function() { 
    var input = document.getElementById("myinputbox").focus(); 
} 
0

嘗試:

的Javascript純:

[elem][n].style.visibility='visible'; 
[elem][n].focus(); 

的Jquery:

[elem].filter(':visible').focus();