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

时间:2012-06-13 12:17:52

标签: javascript jquery focus

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

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

3 个答案:

答案 0 :(得分:5)

您需要覆盖输入元素上的mouseup事件(如this post中所述 - 感谢MrSlayer!)

请参见此处:http://jsfiddle.net/f8TdX/

答案 1 :(得分:1)

这是WebKit中的一个问题。最佳选择是使用focusmouseup事件的组合。以下内容来自another answer类似问题。

$("#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;
    });
});

答案 2 :(得分:0)

试一试

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

Select all contents of textbox when it receives focus (JavaScript or jQuery)

相关问题