方案一:Selection.getCaretIndex() 检测光标位置,查找光标处的单词
//点选单词变色;
function initTextField(_txt) {
_txt.separator = String(" ,.!?'\"\r\n‘’").split("");
Mouse.addListener(_txt);
_txt.onMouseUp = function() {
var word = this.findWordAt(Selection.getCaretIndex());
this.formatText(word.b, word.e);
};
_txt.findWordAt = function(n) {
var str = this.text;
var strA = str.substring(0, n);
var strB = str.substring(n);
var b = 0;
var e = str.length;
for (var i in this.separator) {
var c = this.separator[i];
b = Math.max(b, strA.lastIndexOf(c));
var x = strB.indexOf(c);
if (x != -1) {
e = Math.min(e, x);
}
}
b += 1;
e += n;
return {b:b, e:e, word:str.substring(b, e)};
};
_txt.formatText = function(b, e) {
var format = this.getTextFormat(b, e);
format.color = format.color == 0 ? 0xff0000 : 0;
this.setTextFormat(b, e, format);
};
}
initTextField(TF);
方案二:给每个单词加上锚标签 <a href=\"asfunction:selectWord,"+para+"\">"+obj.word+"</a>"
//点选单词变色;
function initTextField(_txt) {
_txt.formatText = function(b, e) {
var format = this.getTextFormat(b, e);
format.color = format.color == 0 ? 0xff0000 : 0;
this.setTextFormat(b, e, format);
};
var html_str = "";
var str = _txt.text;
var word = "";
var char = "";
var cc = 0;
var arr = [];
var type = "word";
var b = 0;
for (var i = 0; i<str.length; i++) {
char = str.substr(i, 1);
newtype = (isLetter(char) || (str.charCodeAt(i) == 8217 || str.charCodeAt(i) == 39) && isLetter(str.substr(i-1, 1)) && isLetter(str.substr(i+1, 1))) ? "word" : "notword";
if (newtype != type) {
var obj = {b:b, e:i, word:word, type:type};
if (obj.type == "word") {
var para = obj.b+"|"+obj.e+"|"+obj.word;
html_str += "<a href=\"asfunction:selectWord,"+para+"\">"+obj.word+"</a>";
} else {
html_str += obj.word;
}
arr.push(obj);
word = "";
b = i;
type = newtype;
}
char = char == " " ? " " : char;
char = char == "\r" ? "<br/>" : char;
word += char;
}
_txt.html = true;
_txt.htmlText = html_str;
}
function isLetter(char) {
var cc = char.charCodeAt(0);
return (cc>=65 && cc<=90 || cc>=97 && cc<=122);
}
function selectWord(word) {
word = word.split("|");
TF.formatText(Number(word[0]), Number(word[1]));
}
initTextField(TF);
回复Comments
{commenttime}{commentauthor}
{CommentUrl}
{commentcontent}