【问题标题】:Word highlighting in Flash using ActionScript 3.0使用 ActionScript 3.0 在 Flash 中突出显示 Word
【发布时间】:2011-08-02 05:56:56
【问题描述】:

我正在使用 Flash Professional CS4 和 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 );
    }
}

此代码仅在第一次使用标签时有效,但如果再次使用标签,则不会改变颜色。

有什么想法吗?还有什么功能可以用吗?

提前致谢。

【问题讨论】:

    标签: flash actionscript-3 actionscript flash-cs4


    【解决方案1】:

    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] 后面有一个逗号,例如“你好 [NAME],你好吗”,该怎么办?上面的代码会漏掉这些情况。

    【讨论】:

    • startIndex 有效!!但是,是的,你是对的,我没有考虑过这些情况。关于如何找到特定单词的任何好主意?可能一个字一个字看?
    • 使用正则表达式。一个很好的工具在这里:gskinner.com/RegExr 例如,搜索 [AGE] 字符串使用全局标志,正则表达式应该是 /\[AGE\]/g 。要查找 [AGE] 或 [NAME],请使用 /\[AGE\]|\[NAME\]/g
    【解决方案2】:

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

    /\bMyVar\b/g 
    

    这将匹配MyVar 的每一次出现,但前提是它是一个完整的单词。例如,MyVarToo 不会匹配,因为 \b 指的是单词边界。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 2018-10-03
      • 2015-03-04
      • 1970-01-01
      相关资源
      最近更新 更多