Highlighting a piece of string in a TextArea

前端 未结 3 2059
醉话见心
醉话见心 2020-12-18 07:08

I\'m trying to highlight a piece of text in a \"Textarea\". I have a long string in that TextArea:

Lorem ipsum dolor sit amet, consectetur adipisicing elit,          


        
相关标签:
3条回答
  • 2020-12-18 07:43

    Here's some code that will select a range of text in a textarea in all major browsers, including IE 6+:

    function offsetToRangeCharacterMove(el, offset) {
        return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
    }
    
    function setSelection(el, start, end) {
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            el.selectionStart = start;
            el.selectionEnd = end;
        } else if (typeof el.createTextRange != "undefined") {
            var range = el.createTextRange();
            var startCharMove = offsetToRangeCharacterMove(el, start);
            range.collapse(true);
            if (start == end) {
                range.move("character", startCharMove);
            } else {
                range.moveEnd("character", offsetToRangeCharacterMove(el, end));
                range.moveStart("character", startCharMove);
            }
            range.select();
        }
    }
    
    var textarea = document.getElementById("your_textarea");
    var val = textarea.value;
    var start = val.indexOf("ipsum") + 5, end = val.indexOf("consectetur");
    setSelection(textarea, start, end);
    
    0 讨论(0)
  • 2020-12-18 07:43

    I remember seeing this a while ago... http://www.din.or.jp/~hagi3/JavaScript/JSTips/Mozilla/Samples/NSHTMLTextAreaElement.htm

    Its quite complicated and I could never quite be bothered to get my head round it. Dunno if this is what you need, or if you can use it at all. :)

    0 讨论(0)
  • 2020-12-18 07:46

    You can't highlight different parts of text in a textarea. You can select a part but not multiple parts and select is not highlighting. You can take the content of your textarea and but it an <div> for example and highlight the phrases by surrounding them with <span class="highlight">...</span>

    0 讨论(0)
提交回复
热议问题