当您在 textarea 内单击时,如何使其全部内容被选中?
最终当您再次单击时,取消选择它。
当您在 textarea 内单击时,如何使其全部内容被选中?
最终当您再次单击时,取消选择它。
为了防止用户在每次尝试使用鼠标移动插入符号时选择整个文本时感到恼火,您应该使用focus事件而不是click事件来执行此操作。以下将完成这项工作并解决 Chrome 中阻止最简单版本(即仅select()在focus事件处理程序中调用 textarea 的方法)工作的问题。
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;
    });
});
更好的方法,解决 tab 和 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;
            });
        }
    });
我最终使用了这个:
$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});
$('textarea').focus(function() {
    this.select();
}).mouseup(function() {
    return false;
});
稍微短一点的 jQuery 版本:
$('your-element').focus(function(e) {
  e.target.select();
  jQuery(e.target).one('mouseup', function(e) {
    e.preventDefault();
  });
});
它可以正确处理 Chrome 角落案例。有关示例,请参见http://jsfiddle.net/Ztyx/XMkwm/。