2012-07-09 87 views
6

我目前想要關注第一個輸入元素,而不選擇輸入元素中的預設值文本。我怎樣才能集中我的輸入元素,然後取消選中它裏面的文本?我目前關注的jQuery如下。如何聚焦輸入,並取消選擇其中的文字

$(document).ready(function() { 
    $("input[name='title']").focus(); 
}); 
+1

http://stackoverflow.com/questions/794583/deselect-contents-of-a-textbox-with-javascript – 2012-07-09 22:33:20

回答

7
$(document).ready(function() { 
    $("input[name='title']").focus(); 
    $("input[name='title']").val($("input[name='title']").val()); 
}); 
6

您可以使用selectionStartselectionEnd屬性:

$(document).ready(function() { 
    $("input[name='title']").each(function(){ 
     this.focus(); 
     this.selectionEnd = this.selectionStart; 
    }); 
}); 
0
$("input[name='title']").focus(function() 
{ 
    var elem = $(this); 

    elem.val(elem.val()); 
}); 
+0

這也不會工作,我嘗試這些都在Chrome ATM – Solo 2012-07-09 22:38:06

-2

它不買璀璨可以幫助你

JSFiddle

基礎:覆蓋已經存在的內容...

$(document).ready(function() { 
    $('#t1').focus(); 
    $('#t1').val($('#t1').val());      
}); ​ 
2

這是基於Danilo Valente的上面的答案。我發現,在Chrome我不得不打電話this.selectionEnd = this.selectionStart之前,使用一個微小的延遲,否則輸入的文本將保持選中狀態:

這對我的作品在Chrome,Firefox,Safari和IE瀏覽器(測試IE 10)

$("input").focus(function() { 
    var input = this; 
    setTimeout(function() { input.selectionStart = input.selectionEnd; }, 1); 
}); 

這裏有一個演示:http://jsfiddle.net/rangfu/300ah0ax/2/

相關問題