如何使用JavaScript或JQuery在HTML中突出显示输入文本字段的一部分 [英] How to highlight a part part of an Input text field in HTML using Javascript or JQuery

查看:263
本文介绍了如何使用JavaScript或JQuery在HTML中突出显示输入文本字段的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对HTML中的自由输入文本字段进行某种形式的验证。有没有办法在使用JQuery或JavaScript的输入文本字段中突出显示特定的单词或短语(基于特定标准)?

在文本输入框中,仅突出显示文本的一部分的唯一机会就是使用选择。您可以在所有现代浏览器中使用文本框的 selectionStart selectionEnd 属性或 setSelectionRange()方法(不知道为什么都存在)。



现场演示: http://jsfiddle.net/YNr7K/



代码:

  var input = document.getElementById(textBoxId); 
input.value =喝杯茶;
input.setSelectionRange(0,3); // HighlightsCup
input.focus();

在旧版本的IE(< 9)中,您需要使用其中一个令人厌烦的的TextRange 秒。请参阅此答案,了解如何执行此操作的功能。


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?

解决方案

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

Live demo: 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.

这篇关于如何使用JavaScript或JQuery在HTML中突出显示输入文本字段的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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