javascript 如何聚焦输入,并取消选择其中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11404130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:04:19  来源:igfitidea点击:

How to focus input, and deselect text inside it

javascriptjqueryhtmlforms

提问by Solo

I am currently wanting to focus the first input element, without selecting the preset value text inside the input element. How can I focus my input element, and then deselect the text inside it? My current focus jQuery is as follows.

我目前想要聚焦第一个输入元素,而不选择输入元素内的预设值文本。如何聚焦我的输入元素,然后取消选择其中的文本?我目前的重点 jQuery 如下。

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

采纳答案by Chief120

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

回答by Danilo Valente

You can use the selectionStartand selectionEndproperties:

您可以使用selectionStartselectionEnd属性:

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

回答by rangfu

This is based on Danilo Valente's answer above. I found that on Chrome I had to use a tiny delay before calling this.selectionEnd = this.selectionStart, otherwise the input text would remain selected:

这是基于 Danilo Valente 上面的回答。我发现在 Chrome 上我必须在调用之前使用一个很小的延迟this.selectionEnd = this.selectionStart,否则输入文本将保持选中状态:

This works for me on Chrome, Firefox, Safari and IE (tested IE 10)

这适用于我在 Chrome、Firefox、Safari 和 IE 上(经过 IE 10 测试)

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

Here's a demo: http://jsfiddle.net/rangfu/300ah0ax/2/

这是一个演示:http: //jsfiddle.net/rangfu/300ah0ax/2/

回答by Leniel Maccaferri

$("input[name='title']").focus(function()
{ 
    var elem = $(this);

    elem.val(elem.val());
});

回答by esertbas

Its not briliant buy may help you

它不聪明的购买可能会帮助你

JSFiddle

JSFiddle

Basic : Overwrite what is already there...

基本:覆盖已经存在的内容......

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