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

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

问题描述



最后,当您再次单击时,取消选择它。

如何才能使它在单击textarea内部时完成,为了防止用户在每次尝试使用鼠标移动插入符号时选择整个文本时感到恼火,应该停止使用该应用程序使用焦点事件执行此操作,而不是使用点击事件。以下内容将完成这项工作,并解决Chrome中的一个问题,即阻止最简单的版本(即在焦点中调用textarea的 select()方法 event handler)。



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



代码:

 < textarea id =foo>一些文字< / textarea> 

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

//解决Chrome的小问题
textBox.onmouseup = function(){
//防止进一步的mouseup干预
textBox.onmouseup = null;
返回false;
};
};
< / script>

jQuery版本:

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

$解决Chrome的小问题
$ this.mouseup(function(){
//防止进一步的mouseup干预
$ this.unbind(mouseup);
返回false;
});
});


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.

解决方案

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/

Code:

<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 version:

$("#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 - 从textarea中选择所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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