JQuery/JavaScript - 突出显示输入或文本区域中的一部分文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12005057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:02:35  来源:igfitidea点击:

JQuery/JavaScript - highlight a part of text from input or textarea

javascriptjquery

提问by Mirek

Possible Duplicate:
How to highlight a part part of an Input text field in HTML using Javascript or JQuery

可能的重复:
如何使用 Javascript 或 JQuery 在 HTML 中突出显示输入文本字段的一部分

Does anyone know how to highlight some text in input[type=text]or textarea? Is it possible?

有谁知道如何突出显示input[type=text]或 中的某些文本textarea?是否可以?

回答by Ricardo Alvaro Lohmann

You have to place a divbehind your textareaand then style it according to it's text.
Notes:

你必须div在你的后面放置一个textarea,然后根据它的文本设置样式。
注意事项

  • Set your textareabackground-colorto transparent to see your highlightercolor.
  • Your highlighterhave to be the same style and text content of your textareato put the spanon the right place.
  • Set your highlightertext to the same color of it's background or you'll see a <b>effect, the same for the span.
  • 将您设置textareabackground-color为透明以查看您的highlighter颜色。
  • highlighter必须与您的样式和文本内容相同textarea才能将其span放在正确的位置。
  • 将您的highlighter文本设置为与背景相同的颜色,否则您会看到<b>效果,对于span.

html:

html:

<div class="highlighter">some text <span>highlighted</span> some text</div>
<textarea>some text highlighted some text</textarea>

css:

css:

.highlighter, textarea {
    width: 400px;
    height: 300px;
    font-size: 10pt;
    font-family: 'verdana';
}

.highlighter {
    position: absolute;
    padding: 1px;
    margin-left: 1px;
    color: white;
}

.highlighter span {
    background: red;
    color: red;
}

textarea {
    position: relative;
    background-color: transparent;
}

demo

演示

回答by Asciiom

This code snippet shows you how:

此代码片段向您展示了如何:

window.onload = function() {
    var message = document.getElementById('message');
    // Select a portion of text
    createSelection(message, 0, 5);

    // get the selected portion of text
    var selectedText = message.value.substring(message.selectionStart, message.selectionEnd);
    alert(selectedText);
};

function createSelection(field, start, end) {
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end);
        selRange.select();
    } else if( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } else if( field.selectionStart ) {
        field.selectionStart = start;
        field.selectionEnd = end;
    }
    field.focus();
}