網站搜尋

javascript - jQuery - 選取 textarea 中的所有文字


我如何才能讓當你點擊文本區時,其全部內容被選中?

最終當你再次點擊時,以取消選取它。

答案#1

為了防止使用者在每次嘗試使用滑鼠移動插入點時整段文字都被選取而感到困擾,你應該使用 focus 事件來實現,而不是 click 事件。以下方法可以達成目標,並解決 Chrome 中的一個問題,該問題會導致最簡單的版本(即僅在 focus 事件處理器中調用 textarea 的 select() 方法)無法正常運作。

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

答案#2

更好的方式,解決分頁和 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;
            });
        }
    });

答案#3

我最後使用了這個:

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