jQuery - 从文本区域中选择所有文本 [英] jQuery - select all text from a textarea

查看:34
本文介绍了jQuery - 从文本区域中选择所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能做到当你在文本区域内点击时,它的整个内容都会被选中?

How can I make it so when you click inside a textarea, its entire content gets selected?

最终当你再次点击时,取消选择它.

And eventually when you click again, to deselect it.

推荐答案

为了防止用户在每次尝试使用鼠标移动插入符号时都被选中时感到恼火,您应该使用 focus 事件,而不是 click 事件.以下将完成这项工作并解决 Chrome 中阻止最简单版本(即在 focus 事件处理程序中仅调用 textarea 的 select() 方法)工作的问题.

To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus event, not the click event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select() method in a focus event handler) from working.

jsFiddle:http://jsfiddle.net/NM62A/

代码:

<textarea id="foo">Some text</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("foo");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome's little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>

jQuery 版本:

$("#foo").focus(function() {
    var $this = $(this);
    $this.select();

    // Work around Chrome's little problem
    $this.mouseup(function() {
        // Prevent further mouseup intervention
        $this.unbind("mouseup");
        return false;
    });
});

这篇关于jQuery - 从文本区域中选择所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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