2011-04-09 70 views
0

我正在使用Flash Professional CS4和ActionScript 3.0字在Flash中突出使用ActionScript 3.0

比赛很快结束了,我只需要添加一个功能,突出了一些“标签”,如“[NAME]文本编辑器“和”[AGE]“(通过改变颜色)。

我使用的是textField,而不是TextArea组件。这是我使用的代码,但它不能按计划运行。

taMain.addEventListener(Event.CHANGE, checkTags); 
function checkTags(e):void{ 
    var tempFormat:TextFormat = taMain.getTextFormat(taMain.selectionBeginIndex - 1, taMain.selectionEndIndex); 
    var splitText:Array = taMain.text.split(" "); 
    for (var i = 0; i < splitText.lenght; i++) { 
     switch (splitText[i]) { 
      case "[NAME]": 
       tempFormat.color = (0xff0000); 
      break; 
      case "[AGE]": 
       tempFormat.color = (0x0000ff); 
      break; 
      default: 
       tempFormat.color = (0x000000); 
     } 
     taMain.setTextFormat(tempFormat, taMain.text.indexOf(splitText[i]), taMain.text.indexOf(splitText[i]) + splitText[i].length); 
    } 
} 

此代码仅在首次使用标签时起作用,但如果再次使用标签,它不会更改颜色。

任何想法?任何其他功能,我可以使用?

在此先感谢。

回答

0

taMain.text.indexOf(splitText[i])将始终找到第一个出现的单词,如第一个“[NAME]”,并且在第一次出现时设置文本格式,即使for循环出现在另一个“[NAME]” 。

的indexOf()接受可选的第二个参数,索引从开始,所以你可以跟踪文本您当前所在,通过做这样的事情:

var tempFormat:TextFormat = taMain.getTextFormat(taMain.selectionBeginIndex - 1, taMain.selectionEndIndex); 
var splitText:Array = taMain.text.split(" "); 
var startIndex:Number = 0; 
for (var i = 0; i < splitText.length; i++) { 
    switch (splitText[i]) { 
     case "[NAME]": 
      tempFormat.color = (0xff0000); 
     break; 
     case "[AGE]": 
      tempFormat.color = (0x0000ff); 
     break; 
     default: 
      tempFormat.color = (0x000000); 
    } 
    taMain.setTextFormat(tempFormat, taMain.text.indexOf(splitText[i], startIndex), taMain.text.indexOf(splitText[i], startIndex) + splitText[i].length); 
    startIndex = taMain.text.indexOf(splitText[i], startIndex) + splitText[i].length; 
} 

但我不认为在空间上的分裂,就像在var splitText:Array = taMain.text.split(" ")中一样,是在一般文本中查找单词的好方法。如果[AGE]是一行的最后一个词,在它后面有一个换行符,或[NAME]之后有一个逗号,如“Hello [NAME],你好吗”?上面的代码会错过这些事件。

+0

startIndex作品!但是,你说得对,我没有考虑过这些情况。有关如何查找特定单词的好主意?也许看字符一个字符? – 2011-04-09 23:52:18

+0

使用正则表达式。一个很好的工具是在这里:http://www.gskinner.com/RegExr/例如,搜索[AGE]字符串使用全局标志,正则表达式应该是'/ \ [AGE \]/g '。要找到[AGE]或[NAME],请使用'/ \ [AGE \] | \ [NAME \]/g' – sydd 2011-04-10 01:57:45

0

使用正则表达式,如果您的输入处于ASCII范围内,则很容易找到一个单词/短语(例如,没有德语变音符号)。然后,您可以封装你的搜索术语\ B的,像这样:

/\bMyVar\b/g 

这会的MyVar每一次出现匹配,但只有当它是一个整体的话。例如MyVarToo将不匹配,因为\b涉及字边界。