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
JQuery/JavaScript - highlight a part of text from input or textarea
提问by Mirek
Possible Duplicate:
How to highlight a part part of an Input text field in HTML using Javascript or JQuery
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 div
behind your textarea
and then style it according to it's text.
Notes:
你必须div
在你的后面放置一个textarea
,然后根据它的文本设置样式。
注意事项:
- Set your
textarea
background-color
to transparent to see yourhighlighter
color. - Your
highlighter
have to be the same style and text content of yourtextarea
to put thespan
on the right place. - Set your
highlighter
text to the same color of it's background or you'll see a<b>
effect, the same for thespan
.
- 将您设置
textarea
background-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;
}
回答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();
}