jQuery - 从textarea中选择所有文本

时间:2011-04-26 23:12:06

标签: javascript jquery forms textarea selection

当你在textarea里面点击时,我怎么能这样做呢?它的整个内容都被选中了?

最后再次点击时,取消选择它。

6 个答案:

答案 0 :(得分:189)

为了防止用户在每次尝试使用鼠标移动插入符号时选择整个文本时会感到恼火,您应该使用focus事件而不是click事件来执行此操作。以下内容将完成这项工作并解决Chrome中的一个问题,即阻止最简单的版本(即只调用select()事件处理程序中的textarea的focus方法)。

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;
    });
});

答案 1 :(得分:14)

更好的方法,解决方案选项卡和chrome问题以及新的jquery方式

$("#element").on("focus keyup", function(e){

        var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if(keycode === 9 || !keycode){
            // Hacemos select
            var $this = $(this);
            $this.select();

            // Para Chrome's que da problema
            $this.on("mouseup", function() {
                // Unbindeamos el mouseup
                $this.off("mouseup");
                return false;
            });
        }
    });

答案 2 :(得分:11)

我最终使用了这个:

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});

答案 3 :(得分:5)

略短的jQuery版本:

$('your-element').focus(function(e) {
  e.target.select();
  jQuery(e.target).one('mouseup', function(e) {
    e.preventDefault();
  });
});

正确处理Chrome边角。有关示例,请参阅http://jsfiddle.net/Ztyx/XMkwm/

答案 4 :(得分:5)

$('textarea').focus(function() {
    this.select();
}).mouseup(function() {
    return false;
});

答案 5 :(得分:4)

Selecting text in an element (akin to highlighting with your mouse)

:)

使用该帖子上接受的答案,你可以调用这样的函数:

$(function() {
  $('#textareaId').click(function() {
    SelectText('#textareaId');
  });
});
相关问题