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

时间:2022-11-29 12:38:40

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在输入文本字段中突出显示特定的单词或短语(基于特定的标准)?

1 个解决方案

#1


16  

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 TextRanges. See this answer for a function that shows how to do this.

在旧版本的IE(< 9)中,您需要使用其中一个烦人的TextRanges。请参见这个函数的答案,该函数演示了如何执行此操作。

#1


16  

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 TextRanges. See this answer for a function that shows how to do this.

在旧版本的IE(< 9)中,您需要使用其中一个烦人的TextRanges。请参见这个函数的答案,该函数演示了如何执行此操作。