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

时间:2012-07-09 22:29:38

标签: javascript jquery html forms

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

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

6 个答案:

答案 0 :(得分:10)

您可以使用selectionStartselectionEnd属性:

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

答案 1 :(得分:7)

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

答案 2 :(得分:4)

这是基于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/

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

想添加一些增强的解决方案,该解决方案也关心取消选择时的实际插入符号定位。

我使用了以下 input 元素方法:

<input (blur)="onLocalFocusOut()" (click)="onInputClick($event)" (mousedown)="onMouseDown($event)" />

方法如下:

public onInputClick(event: MouseEvent): void {
    if (!this._initialSelectAll) {
        (event.target as HTMLInputElement).select();
        this._initialSelectAll = true;
    }
}

public onMouseDown(event: MouseEvent): void {
    if (this._initialSelectAll) {
        (event.target as HTMLInputElement).selectionStart = (event.target as HTMLInputElement).selectionEnd = 0;
    }
}

public onLocalFocusOut(): void {
    this._initialSelectAll = false;
    this.onFocusChange(false);
}

这样的设置确保对于 click 元素中的每个第一个 input,所有字段内容都将被选中。任何后续 click 将清除选择并将插入符号定位在实际鼠标单击坐标处。每当 input 元素失去焦点时,此逻辑将重新初始化。

htmlcode 是为 angular 2+ 编写的,但很容易将其适应任何其他编码框架。

答案 5 :(得分:-2)

它并不精彩,但可以帮助你

JSFiddle

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

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