如何在Adobe InDesign中将app.selection [0]用于脚本

5 javascript adobe adobe-indesign

我想通过仅测试当前选择(而不是整个文档)来运行代码,而我很难确切了解数组“ app.selection”及其方法的工作方式。首先,我使用“ for”循环通过使用以下命令循环选择每个项目:

for(loop = 0; loop < app.selection.length; loop++){
    var sel = loop;
}
Run Code Online (Sandbox Code Playgroud)

这样做可以,但是当我想确定每个项目是什么时,它会变得有些奇怪。例如,

for(txt = 0; txt < app.selection[sel].textFrames.length; txt++){
    // do something to each text frame in the selection here.
}
Run Code Online (Sandbox Code Playgroud)

不能按预期工作,但是

for(img = 0; img < app.selection[sel].allGraphics.length; img++){
    // do something to each graphic in the selection here
}
Run Code Online (Sandbox Code Playgroud)

无论选择内容是否仅包含图形,还是包含在组内还是组外,似乎都能很好地工作。

有时,似乎app.selection [0]是独自访问项目的唯一方法。换句话说,如果选择了文本框架,则app.selection [0]可能与app.document.textFrames [0]相同,在这种情况下,重复地说(而且不正确)

app.document.textFrames[0].textFrames[0]
Run Code Online (Sandbox Code Playgroud)

但是,在不同页面项上使用相同的概念就像是一种魅力。遵循是相当令人困惑的。此外,似乎无法确定该物品是哪种对象。我想说些类似的话:

if (app.selection[0] == [object TextFrame])
Run Code Online (Sandbox Code Playgroud)

但这似乎对我不起作用。有没有一种方法可以清楚地测试当前项目是组,图形还是文本框架,并根据结果执行不同的操作?

Chr*_*ina 5

app.selection 返回一个对象数组,因此数组中的每个项目可以是不同的类型,并且可用的属性和方法也不同。使用 Extendscript Javascript 控制台时,您只需键入以下内容即可动态查看数组中的特定项目

app.selection[0]
Run Code Online (Sandbox Code Playgroud)

(或任何数字)。结果将类似于 [object TextFrame]。

在循环选择数组时,您可以使用 app.selection[0].constructor.name 来确定每个数组的类型。或者,如果您只对某些类型感兴趣,

if (app.selection[i] instanceof TextFrame){}
Run Code Online (Sandbox Code Playgroud)

那时,您将更多地了解可以访问哪些属性(具体取决于类型)。

要回答问题的第二部分,没有 allTextFrames 属性,但有 allPageItems 属性。这会返回一个 pageItems 数组(textFrames、组等),您可以像 app.selection 一样使用它。因此,如果我在文档的第一页上分组了三个文本框架(没有其他内容),我可以看到以下内容都是正确的:

app.activeDocument.pages[0].textFrames.length == 0;
app.activeDocument.pages[0].allPageItems.length == 4;
app.activeDocument.pages[0].allPageItems[0] instanceof Group;
app.activeDocument.pages[0].allPageItems[1].constructor.name == "TextFrame";
Run Code Online (Sandbox Code Playgroud)

因此,如果该数组比 textFrames 集合对您更有用,您可以循环遍历该数组。请记住,您无权访问 TextFrames 的特殊集合属性(如 everyItem())。