【问题标题】:Finding the top level Layerset in Photoshop using Javascript使用 Javascript 在 Photoshop 中查找顶级图层集
【发布时间】:2019-01-13 05:08:59
【问题描述】:

我当前的代码很糟糕,这是周五下午的特别节目:

if(layer.parent == doc && isLayerSet) {  
 //do something in this case fileNew.write('foo');  
}  
else if(layer.parent.parent == doc && isLayerSet) {  
 //do something in this case fileNew.write('foo');  
}  
else if(layer.parent.parent.parent == doc && isLayerSet) {  
 //do something in this case fileNew.write('foo');  
}  
else if(layer.parent.parent.parent.parent == doc && isLayerSet) {  
 //do something in this case fileNew.write('foo');  
}  
else if(layer.parent.parent.parent.parent.parent == doc && isLayerSet) {  
 //do something in this case fileNew.write('foo');  
}  
else if(layer.parent.parent.parent.parent.parent.parent == doc && isLayerSet) 
{  
 //do something in this case fileNew.write('foo');  
}  

我这样做是作为概念验证,以查看脚本的其余部分是否有效(确实如此)。

游戏的目的是我想获得它的顶级父级(即文档的第一个子级)的名称。所有块都应该做同样的事情。

我知道有一种更简单的方法可以做到这一点,但是我对此还是很陌生,我不确定 javascript 和 Photoshop 的一些细微差别,所以任何帮助都将不胜感激!

【问题讨论】:

  • 所有的块都一样吗? //do something in this case fileNew.write('foo'); ?
  • 是的,很抱歉我没有提到这一点。我会修改它

标签: javascript scripting photoshop


【解决方案1】:

你可以做一些递归的事情。它可以替换所有“if-else if”语句。

(function getTopLayer(element) {
  if (element.parent == doc && isLayerSet) {
    //do something in this case fileNew.write('foo'); 
  } else {
    getTopLayer(element.parent);
  }
})(layer);

但请注意,这将无限运行,直到第一个 if 为真。

【讨论】:

    【解决方案2】:

    您可能只是使用循环将链中的当前parent 分配给一个变量,直到该变量等于doc,或者直到达到允许的最大父级数:

    function doTheThing(layer) {
      if (!isLayerSet) return;
      var currentLayer = layer;
      for (var parentCount = 0; parentCount < 6; parentCount++) {
        currentLayer = layer.parent;
        if (currentLayer === doc) {
          // do something
          // function call here for better readability
          return;
        }
      }
    }
    

    【讨论】:

    • 工作出色,但我确实认为@andrei-rosu 的回答更符合我的要求。谢谢
    猜你喜欢
    • 2013-08-28
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多