我想突出显示div标签的文本。
当有一行但不适用于多行时,它可以工作:
function SelectChar(el, iStart, iLength) {
var div = el
if (document.createRange) {
var textNode = div.firstChild;
if (textNode.data.length > 1) {
var rangeObj = document.createRange();
rangeObj.setStart(textNode, iStart);
rangeObj.setEnd(textNode, iLength);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(rangeObj);
}
}
}
其中textbox
是内容可编辑的div标记。
更新
<div contenteditable="true" id="textbox">The
text
is given
and</div>
有什么建议吗?
这是用于建议单词的插件auto.js
..我想在div标签中为多行文本做选择部分
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {
// debugger
//check for support of typeahead functionality
var range = document.createRange();
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
if (selection) {
var lastSpace = this.textbox.innerText.lastIndexOf(" ");
var lastQuote = this.textbox.innerText.lastIndexOf("'");
var lastHypen = this.textbox.innerText.lastIndexOf("-");
var lastDoubleQuote = this.textbox.innerText.lastIndexOf('"');
var lastEnter = this.textbox.innerText.lastIndexOf("\n");
var lastIndex = Math.max(lastSpace, lastEnter, lastQuote, lastHypen, lastDoubleQuote) + 1;
var contentStripped = this.textbox.innerText.substring(0, lastIndex);
var lastWord = this.textbox.innerText.substring(lastIndex, this.textbox.innerText.length);
this.textbox.innerText = contentStripped + sSuggestion; //.replace(lastWord,"");
var start = this.textbox.innerText.length - sSuggestion.replace(lastWord, "").length;
var end = this.textbox.innerText.length;
SelectChar(document.getElementById("textbox"), start, end);
}
};