[英]JS/jQuery: How to highlight or select a text in a textarea?
I don't want to highlight text (by changing background color to yellow - NO), I just want to select a portion of the text inside textarea, exactly as if the user clicked and hold the click then moved the mouse to highlight only a portion of the text 我不想突出显示文本(通过将背景颜色更改为黄色 - 否),我只想在textarea中选择文本的一部分,就像用户单击并按住单击然后移动鼠标以仅突出显示一个部分文字
How to do that? 怎么做? is it possible?
可能吗?
http://help.dottoro.com/ljtfkhio.php http://help.dottoro.com/ljtfkhio.php
Example 1 would be relevant in your case: 示例1与您的案例相关:
function Select () {
var input = document.getElementById ("myText");
if (input.selectionStart === undefined) { // Internet Explorer
var inputRange = input.createTextRange ();
inputRange.moveStart ("character", 1);
inputRange.collapse ();
inputRange.moveEnd ("character", 1);
inputRange.select ();
}
else { // Firefox, Opera, Google Chrome and Safari
input.selectionStart = 1;
input.selectionEnd = 2;
input.focus ();
}
}
In non-IE browsers, this is easy: you can set the values of the textarea's selectionStart
and selectionEnd
properties, or use the setSelectionRange()
function (although I've never been clear why that method is present: it seems unnecessary). 在非IE浏览器中,这很简单:您可以设置textarea的
selectionStart
和selectionEnd
属性的值,或使用setSelectionRange()
函数(虽然我从来没有清楚为什么存在该方法:它似乎是不必要的)。 In IE, however, it's a bit more complicated. 然而,在IE中,它有点复杂。 Here's a cross-browser function that does it:
这是一个跨浏览器的功能:
var setInputSelection = (function() {
function offsetToRangeCharacterMove(el, offset) {
return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
}
return function(el, startOffset, endOffset) {
el.focus();
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
el.selectionStart = startOffset;
el.selectionEnd = endOffset;
} else {
var range = el.createTextRange();
var startCharMove = offsetToRangeCharacterMove(el, startOffset);
range.collapse(true);
if (startOffset == endOffset) {
range.move("character", startCharMove);
} else {
range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset));
range.moveStart("character", startCharMove);
}
range.select();
}
};
})();
var textarea = document.getElementById("foo");
// Select the text between the second and third characters inclusive
setInputSelection(textarea, 1, 3);
you can use this plugin 你可以使用这个插件
http://www.dennydotnet.com/post/TypeWatch-jQuery-Plugin.aspx http://www.dennydotnet.com/post/TypeWatch-jQuery-Plugin.aspx
you have a callback function after the user has "finished" typing , and more things.. 用户“完成”输入后有一个回调函数,还有更多东西..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.