我正在使用auto.js自动提供单词,因为我必须选择单词...
function SelectChar(el, start, end) { //el=document.getElementById(textbox) start=3 and end=5
var div = el;
var textNode = div.firstChild;
if (textNode.data.length > 1) {
var rangeObj = document.createRange();
rangeObj.setStart(textNode, start);
rangeObj.setEnd(textNode, end);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(rangeObj);
}
}
当我按Enter
时,它会两次添加<br></br>
<div id="textbox" contenteditable="true">hi<br><br>the</div>
但由于div.firstChild
,选择范围在第二行不起作用..我想在<br>
之后用替换行来选择哪些选项...请告诉我任何想法......
jsfiddle(实际代码)
答案 0 :(得分:1)
您可以使用 window.getSelection(); 和 selection.anchorNode;
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {
// debugger
var selection = window.getSelection();
var anchorNode = selection.anchorNode;
var lastSpace = anchorNode.textContent.lastIndexOf(" ");
var lastQuote = anchorNode.textContent.lastIndexOf("'");
var lastHypen = anchorNode.textContent.lastIndexOf("-");
var lastDoubleQuote = anchorNode.textContent.lastIndexOf('"');
var lastEnter = anchorNode.textContent.lastIndexOf("\n");
var lastIndex = Math.max(lastSpace, lastEnter, lastQuote, lastHypen, lastDoubleQuote) + 1;
var contentStripped = anchorNode.textContent.substring(0, lastIndex);
var lastWord = anchorNode.textContent.substring(lastIndex, anchorNode.textContent.length);
anchorNode.textContent = contentStripped + sSuggestion;
var start = anchorNode.textContent.length - sSuggestion.replace(lastWord, "").length;
var end = anchorNode.textContent.length;
SelectChar(anchorNode, start, end);
};
并使用 selection.getRangeAt(0);
function SelectChar(el, iStart, iLength) {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
range.setStart(el, iStart);
range.setEnd(el, iLength);
selection.removeAllRanges();
selection.addRange(range);
}
我认为您最好只关注当前输入选择。
wordSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/) {
var aSuggestions = [];
var selection = window.getSelection();
var anchorNode = selection.anchorNode;
var sTextbox = anchorNode.textContent;
var sTextboxSplit = sTextbox.split(/[\s,]+/);
var sTextboxLast = sTextboxSplit[sTextboxSplit.length - 1];
var sTextboxValue = sTextboxLast;
if (sTextboxValue.length > 0) {
//search for matching words
for (var i = 0; i < this.words.length; i++) {
if (this.words[i].indexOf(sTextboxValue.toLowerCase()) == 0) {
if (this.words[i].indexOf(sTextboxValue) == 0) {
aSuggestions.push(this.words[i]);
}
else if (this.words[i].indexOf(sTextboxValue.charAt(0).toLowerCase() + sTextboxValue.slice(1)) == 0) {
aSuggestions.push(this.words[i].charAt(0).toUpperCase() + this.words[i].slice(1));
}
}
}
}
//provide suggestions to the control
oAutoSuggestControl.autosuggest(aSuggestions);
};
这是一个现场演示,从你的来源分叉和修改。 http://jsfiddle.net/soonsuweb/bcpy0wjn/