[英]Selecting Part of String inside an Input Box with jQuery
我试图弄清楚如何使用jQuery在输入框中仅突出显示文本的一部分。 突出显示输入框的全部内容非常简单,但是如何仅突出显示一个单词或几个字母呢?
谢谢!
对于文本<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">
您将需要选择整个值,然后在代码中处理字符串。 根据您要使用的单词,您可能会考虑使用正则表达式来匹配某些单词/字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.