简体   繁体   中英

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

I don't want to highlight text (by changing background color to yellow - NO), I just want to select a portion of the text inside textarea, exactly as if the user clicked and hold the click then moved the mouse to highlight only a portion of the text

How to do that? is it possible?

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

Example 1 would be relevant in your case:

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

In non-IE browsers, this is easy: you can set the values of the textarea's selectionStart and selectionEnd properties, or use the setSelectionRange() function (although I've never been clear why that method is present: it seems unnecessary). In IE, however, it's a bit more complicated. Here's a cross-browser function that does it:

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

you can use this plugin

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

you have a callback function after the user has "finished" typing , and more things..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM