求助:如何修改Illustrator颜色替换脚本使其仅处理选中对象
修改Illustrator脚本以仅替换选中对象的颜色
没问题,我帮你调整这段脚本,让它只作用于你选中的对象,而不是整个图层的所有元素。
修改后的完整代码
// 定义要查找和替换的RGB颜色 var findColor = new RGBColor(); findColor.red = 180; findColor.green = 90; findColor.blue = 90; var setColor = new RGBColor(); setColor.red = 90; setColor.green = 180; setColor.blue = 180; // 遍历当前选中的所有对象 for (var i = 0; i < app.activeDocument.selection.length; i++) { var item = app.activeDocument.selection[i]; // 只处理带有RGB填充色的路径对象(避免非路径元素报错) if (item.typename === "PathItem" && item.fillColor.typename === "RGBColor") { // 四舍五入颜色值进行匹配(规避Illustrator浮点精度问题) var itemRed = Math.round(item.fillColor.red); var itemGreen = Math.round(item.fillColor.green); var itemBlue = Math.round(item.fillColor.blue); if (itemRed === findColor.red && itemGreen === findColor.green && itemBlue === findColor.blue) { $.writeln("已替换选中对象 #" + i + " 的颜色"); item.fillColor = setColor; } } }
关键修改说明
- 切换遍历目标:把原脚本中遍历整个图层
layer.pathItems的逻辑,改成遍历app.activeDocument.selection——这是Illustrator脚本中获取当前选中对象集合的标准方式。 - 增加安全判断:添加了对象类型和颜色类型的校验,避免选中文字、群组这类非路径对象时脚本报错,同时确保只处理RGB模式的填充色。
- 保留精度兼容:保留了你原有的颜色值四舍五入逻辑,解决Illustrator中颜色值可能出现的浮点偏差问题(比如实际存储为180.0001而非精准的180)。
使用步骤
- 在Illustrator中选中需要修改颜色的对象
- 打开「窗口 > 扩展功能 > 脚本」,运行这段脚本
- 脚本会自动替换选中对象中符合目标颜色的填充色
内容的提问来源于stack exchange,提问作者Muhammad b
相关产品推荐
相关产品推荐

