所以,目前我有一個文本輸入字段,其值也是自動對焦的。把光標放在文本輸入值的末尾
在頁面加載時,該值被選中/突出顯示。有沒有一種方法可以將光標放在值文本的末尾,而不是在javascript或CSS中突出顯示它?
這裏是一個JS提琴,其中自動聚焦文本的價值被突出顯示:http://jsfiddle.net/TaGL5/
下面是HTML代碼:<input type="text" value="value text" autofocus />
所以,目前我有一個文本輸入字段,其值也是自動對焦的。把光標放在文本輸入值的末尾
在頁面加載時,該值被選中/突出顯示。有沒有一種方法可以將光標放在值文本的末尾,而不是在javascript或CSS中突出顯示它?
這裏是一個JS提琴,其中自動聚焦文本的價值被突出顯示:http://jsfiddle.net/TaGL5/
下面是HTML代碼:<input type="text" value="value text" autofocus />
這對我的作品
<input type="text" autofocus value="value text" onfocus="this.value = this.value;"/>
使用JQuery爲此:
$(function() {
var input = $("#txt1");
var len = input.val().length;
input[0].focus();
input[0].setSelectionRange(len, len);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="txt1" value="Lorem" style="width:400px;" />
但有些瀏覽器不支持enter code here
財產,在這種情況下使用:
$(document).ready(function(){
$("#search").focus(function(){
if (this.setSelectionRange)
{
var len = $(this).val().length;
this.setSelectionRange(len, len);
}
else
{
$(this).val($(this).val());
}
});
$("#search").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="search" type="text" value="mycurrtext" size="30" name="search" />
這個問題已經存在於計算器:
使用第三方庫進行如此簡單的任務有點矯枉過正 – shi
升級到@戒的回答是:我發現,做與Firefox的解決方案的工作, 我們需要臨時重置價值「不等於值」,然後將其設置回
<input type="text" autofocus value="value text" onfocus="var temp_value=this.value; this.value=''; this.value=temp_value" />
您可以將此參數添加到您的文本輸入字段:
onmouseover="this.setSelectionRange(this.value.length,this.value.length);"
NB:在2017年
的onfocus Chromium下效果很好= 「THIS.VALUE = THIS.VALUE;」 –
onfocus「this.value = this.value」將爲文本框指定現有值,就像您輸入文本一樣,因此您的光標位於最後。 – VishalDevgire
[使用JavaScript將光標置於文本末尾的文本輸入元素]的可能重複(http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text- in-text-input-element) – Gary