字段选择所有文本,然后在焦点上取消选择它

field selects all text then unselects it on focus

本文关键字:选择 焦点 取消 文本 字段 然后      更新时间:2023-09-26

试图弄清楚为什么会发生这种情况 - 我有一个输入文本字段,我希望当字段获得焦点时突出显示所有文本。这种情况发生得非常快,然后所有文本都被取消选中。知道为什么会这样吗?这是我使用的代码:

$("#permalink").focus(function(){
    this.select();
});

您需要覆盖输入元素上的 mouseup 事件(如本文所述 - 感谢 MrSlayer!

例如,请参阅此处:http://jsfiddle.net/f8TdX/

这是

WebKit中的一个问题。最佳选择是结合使用focusmouseup事件。以下来自对类似问题的另一个答案。

$("#permalink").focus(function() {
    var $this = $(this);
    $this.select();
    window.setTimeout(function() {
        $this.select();
    }, 1);
    // Work around WebKit's little problem
    $this.mouseup(function() {
        // Prevent further mouseup intervention
        $this.unbind("mouseup");
        return false;
    });
});

试一试

$(document).ready(function() {
    $("input:text").focus(function() { $(this).select(); } );
});

在文本框收到焦点时选择文本框的所有内容(JavaScript 或 jQuery)