简体   繁体   English

使用jQuery在输入框中选择字符串的一部分

[英]Selecting Part of String inside an Input Box with jQuery

I am trying to figure out how to highlight just some part of text inside an input box using jQuery. 我试图弄清楚如何使用jQuery在输入框中仅突出显示文本的一部分。 It's quite simple to highlight the entire contents of the input box but how do you highlight just one word or couple of letters? 突出显示输入框的全部内容非常简单,但是如何仅突出显示一个单词或几个字母呢?

Thanks! 谢谢!

For text <input> elements, the following will do the job. 对于文本<input>元素,将执行以下操作。 The example selects just the word "two" in the input: 该示例在输入中仅选择单词“ two”:

 function setInputSelection(input, startPos, endPos) { input.focus(); if (typeof input.selectionStart != "undefined") { input.selectionStart = startPos; input.selectionEnd = endPos; } else if (document.selection && document.selection.createRange) { // IE branch input.select(); var range = document.selection.createRange(); range.collapse(true); range.moveEnd("character", endPos); range.moveStart("character", startPos); range.select(); } } document.getElementById("setSelection").onmousedown = function() { var input = document.getElementById("i"); setInputSelection(input, 4, 7); return false; }; 
 <input id="i" type="text" value="One two three"> <input type="button" value="Set selection" id="setSelection"> 

You will need to select the entire value, and then manipulate the string in code. 您将需要选择整个值,然后在代码中处理字符串。 Depending on what you're trying to do with the words, you might look in to using regular expressions to match certain words/letters. 根据您要使用的单词,您可能会考虑使用正则表达式来匹配某些单词/字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM