Javascript:跨浏览器解决方案,用于选择焦点上文本框内的所有文本 [英] Javascript: cross browser solution for selecting all text inside a textbox on focus

查看:71
本文介绍了Javascript:跨浏览器解决方案,用于选择焦点上文本框内的所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循以下功能:


  • 用户点击或标签到文本框

  • 文本框中的所有文本都被选中,除非文本框已经有焦点,在这种情况下应该发生默认的点击/选择功能

这可能吗?



这适用于Firefox 5

$('input[type="text"]').live('focus', function () {
    this.select();
});

http://jsfiddle.net/HmQxZ/13/

Chrome和IE8选择所有文本只需一瞬间



这适用于Chrome浏览器

Chrome and IE8 selects all the text for only a split second


This works* in Chrome

$('input[type="text"]').live('click', function () {
    this.select();
});

http://jsfiddle.net/HmQxZ/12/

Firefox和IE8选择所有文本,但在后续点击时,文本仍保持选中状态。

Firefox and IE8 selects all text but upon subsequent clicking, the text remains selected.

*种类有效,在文本框有焦点后,单击它会在选择所有文本和能够点击闪烁的插入符号所在的位置之间切换。这可能是可以接受的。

*kind of works, after textbox has focus, clicking on it alternates between selecting all text and being able to click where the blinking caret goes. This is probably acceptable.

推荐答案

setTimeout :

$('input[type="text"]').live('focus', function() {
    var inp = this;
    setTimeout(function() {
        inp.select();
    }, 1);
});

http://jsfiddle.net/HmQxZ/14/

在您选择之后,其他一些浏览器事件正在设置选择文本。因此,等待一毫秒后,您将完成所有浏览器事件,然后选择文本。现在没有什么可以解除它。

What's happening is some other browser event is setting the selection after you've selected the text. So, by waiting a millisecond, you let all the browser events finish, and then select the text. Nothing will undo it now.

这篇关于Javascript:跨浏览器解决方案,用于选择焦点上文本框内的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆