簡體   English   中英

JS / jQuery:如何在textarea中突出顯示或選擇文本?

[英]JS/jQuery: How to highlight or select a text in a textarea?

我不想突出顯示文本(通過將背景顏色更改為黃色 - 否),我只想在textarea中選擇文本的一部分,就像用戶單擊並按住單擊然后移動鼠標以僅突出顯示一個部分文字

怎么做? 可能嗎?

http://help.dottoro.com/ljtfkhio.php

示例1與您的案例相關:

        function Select () {
            var input = document.getElementById ("myText");
            if (input.selectionStart === undefined) {   // Internet Explorer
                var inputRange = input.createTextRange ();
                inputRange.moveStart ("character", 1);
                inputRange.collapse ();
                inputRange.moveEnd ("character", 1);
                inputRange.select ();
            }
            else {      // Firefox, Opera, Google Chrome and Safari
                input.selectionStart = 1;
                input.selectionEnd = 2;
                input.focus ();
            }
        }

在非IE瀏覽器中,這很簡單:您可以設置textarea的selectionStartselectionEnd屬性的值,或使用setSelectionRange()函數(雖然我從來沒有清楚為什么存在該方法:它似乎是不必要的)。 然而,在IE中,它有點復雜。 這是一個跨瀏覽器的功能:

var setInputSelection = (function() {
    function offsetToRangeCharacterMove(el, offset) {
        return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
    }

    return function(el, startOffset, endOffset) {
        el.focus();
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            el.selectionStart = startOffset;
            el.selectionEnd = endOffset;
        } else {
            var range = el.createTextRange();
            var startCharMove = offsetToRangeCharacterMove(el, startOffset);
            range.collapse(true);
            if (startOffset == endOffset) {
                range.move("character", startCharMove);
            } else {
                range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset));
                range.moveStart("character", startCharMove);
            }
            range.select();
        }
    };
})();

var textarea = document.getElementById("foo");

// Select the text between the second and third characters inclusive
setInputSelection(textarea, 1, 3); 

你可以使用這個插件

http://www.dennydotnet.com/post/TypeWatch-jQuery-Plugin.aspx

用戶“完成”輸入后有一個回調函數,還有更多東西..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM