突出显示TextArea中的一段字符串 [英] Highlighting a piece of string in a TextArea

查看:93
本文介绍了突出显示TextArea中的一段字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图突出显示Textarea中的一段文字。
TextArea中有一个很长的字符串:

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, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident

我有一个函数可以提取第一个出现在开始和结束变种。例如:

And I have a function that can extract the first string occurrence that is between the "begin" and "end" vars. For example:

extract("ipsum", "consectetur") // This will give: "dolor sit amet,"

但是,我想要的是选择函数的结果,以便生成的字符串dolor sit amet, 将突出显示。

But, what I want is to select the result of the function so the resulting string "dolor sit amet," will be highlighted.

可能吗?
我该怎么做?

Is it possible? How can I do this?

谢谢,

问候。

推荐答案

这里有一些代码可以在所有主流浏览器(包括IE 6 +)的textarea中选择一系列文本:

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

这篇关于突出显示TextArea中的一段字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆