Indesign脚本问题:查找文本框、添加文本及设置文字颜色(已实现文本添加)
Great job getting the text added to your targeted text frame already! Changing the text color just requires working with the text's character properties—here's how to pull it off smoothly:
Step 1: Target the text range of your frame
When you set myFrame.contents, you’ve added the text, but to adjust its color, you need to access the text range of that frame. The simplest way to target all text in the frame is:
// Your existing working code var myFrame = app.activeDocument.textFrames.itemByName("test"); myFrame.contents = "hello world"; // Grab the full text content of the frame var targetText = myFrame.texts[0];
Step 2: Apply your desired text color
You have two straightforward options here, depending on whether you’re using an existing color swatch or creating a custom one:
Option A: Use an existing document swatch
If you already have a color swatch (like "Navy" or "Bright Red") set up in your InDesign document, reference it directly:
// Replace "YourSwatchName" with your actual swatch name targetText.fillColor = app.activeDocument.colors.itemByName("YourSwatchName");
Option B: Create a custom color programmatically
If you need to define a new color on the fly, create a swatch first, then apply it:
// Create a new RGB color swatch var customTeal = app.activeDocument.colors.add(); customTeal.name = "CustomTeal"; customTeal.colorType = ColorType.RGB; customTeal.rgbRed = 0; customTeal.rgbGreen = 150; customTeal.rgbBlue = 136; // Apply the custom color to your text targetText.fillColor = customTeal;
Bonus: Color only part of the text
If you don’t want to color the entire frame’s text, you can target specific characters, words, or ranges:
// Color only the first 6 characters ("hello ") targetText.characters.itemByRange(0, 5).fillColor = customTeal;
A quick reminder: Use fillColor for the text’s actual color—strokeColor would only color the outline of the text, which is probably not what you want here.
内容的提问来源于stack exchange,提问作者lanes123

