我正在尝试弄清楚如何使用 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">
关于javascript - 使用 jQuery 在输入框中选择字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50163878/