You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Adobe Illustrator脚本求助:文本框及文本选中状态判断异常

解决方案

问题根源

原代码依赖嵌套try/catch块判断选中状态,这种方式不可靠:当未选中任何内容时,$docRef.selection是空数组,访问selection[0]会触发e1异常;但在e1的catch块中访问selection.parent时,空数组本身没有parent属性,抛出的异常因Illustrator脚本环境特性,未被内层e2捕获,导致第三种状态逻辑无法执行。

重构后的代码(明确条件判断)

通过直接判断选中对象的类型和数量区分三种状态,避免依赖try/catch做逻辑分支:

if (app.documents.length > 0) {
    var $docRef = app.activeDocument;
    var $rslt = "I am the replacement value";
    var selection = $docRef.selection;

    // 状态3:未选中任何文本框或文本内容
    if (selection.length === 0) {
        alert("Creating new Text Frame");
        // 创建新文本框并赋值
        var newTextFrame = $docRef.textFrames.add();
        newTextFrame.contents = $rslt;
        // 可选:设置文本框位置为文档居中
        newTextFrame.top = $docRef.height / 2;
        newTextFrame.left = $docRef.width / 2;
    } 
    // 状态1:选中了文本框本身
    else if (selection[0].typename === "TextFrame") {
        selection[0].contents = $rslt;
    } 
    // 状态2:光标在文本框内或选中了部分文本
    else {
        var selectedItem = selection[0];
        // 文本选中时,选中对象的父级为Story(文本容器)
        if (selectedItem.parent && selectedItem.parent.typename === "Story") {
            // 替换文本框内容,若要插入而非替换可改为 += $rslt
            selectedItem.parent.contents = $rslt;
        }
    }
}

代码说明

  • 状态3判断:先检查selection.length === 0,直接处理未选中任何内容的场景,逻辑最清晰。
  • 状态1判断:选中对象的typename为TextFrame时,直接替换文本框内容。
  • 状态2判断:文本框内的选中内容(字符、单词等)的父级是Story,通过父级类型确认文本选中状态,再修改对应内容。

原代码嵌套Catch不触发的原因

未选中任何内容时,$docRef.selection是空数组,在e1的catch块中访问selection.parent时,空数组无parent属性会抛出异常,但Illustrator脚本引擎会将该异常直接抛至全局,未被内层try/catch捕获,导致e2逻辑无法执行。用明确的条件判断可彻底规避这类问题。

内容的提问来源于stack exchange,提问作者Reinhardt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:36:06