如何使用 Javascript 或 JQuery 在 HTML 中突出显示输入文本字段的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10341843/
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
How to highlight a part part of an Input text field in HTML using Javascript or JQuery
提问by user6123723
I'm performing some form of validation on a freely typed input text field in HTML. Is there a way to highlight certain words or phrases (based on certain criteria) in a input text field using JQuery or JavaScript?
我正在对 HTML 中自由键入的输入文本字段执行某种形式的验证。有没有办法使用 JQuery 或 JavaScript 在输入文本字段中突出显示某些单词或短语(基于某些条件)?
回答by Tim Down
Within a text input box, your only opportunity for highlighting just a part of the text is using the selection. You can do this in all modern browsers with the text box's selectionStart
and selectionEnd
properties, or setSelectionRange()
method (no idea why both exist).
在文本输入框中,突出显示部分文本的唯一机会是使用选择。您可以在所有现代浏览器中使用文本框selectionStart
和selectionEnd
属性或setSelectionRange()
方法(不知道为什么两者都存在)来执行此操作。
Live demo: http://jsfiddle.net/YNr7K/
现场演示:http: //jsfiddle.net/YNr7K/
Code:
代码:
var input = document.getElementById("textBoxId");
input.value = "Cup of tea";
input.setSelectionRange(0, 3); // Highlights "Cup"
input.focus();
In older versions of IE (< 9), you'll need to use one of their tiresome TextRange
s. See this answerfor a function that shows how to do this.
在较旧版本的 IE (< 9) 中,您需要使用它们令人厌烦的TextRange
s 之一。有关显示如何执行此操作的函数,请参阅此答案。