该闪就闪
-=本人学习flash过程中做的一些实验品=-

点选单词变色

   Flash习作2009-2-1 15:29

方案一: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 == " " ? "&nbsp;" : 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);

标签集:TAGS:flash ActionScript
回复Comments()点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}
我的日历
分类日志
友情链接
最新评论
搜索日志
访问计数
获取 RSS
我的 Blog:
jh7086 最新的 20 条日志
[Flash习作]
[Flash进修]
[Flash推荐]
[Flash涂鸦]
[听~音乐]
[我滴地盘er]
全站 Blog:
全站最新的 20 条日志
Powered by 5DBlog.com