2012-07-09 81 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/

相关问题