放置两个矩形的优雅方式

| 我有一个矩形(称为目标),并希望在其旁边放置另一个矩形(称为卫星)。卫星的位置(上,下,左,右)确定相对于目标的放置边缘。它还具有对齐方式(左,中,右为顶部和底部位置,顶部,中部和底部为左侧和右侧位置)。 例:
+----------+----------------------------+
|          |                            |
|  Target  | Satellite, Position=RIGHT, |
|          | Align=TOP                  |
|          |                            |
|          |----------------------------+
|          |
+----------+
我知道目标的左上角坐标及其宽度和高度。我也知道卫星的宽度和高度,并想计算它的左上角坐标。我可以通过一系列12个
if
子句来做到这一点,但是也许有更优雅,数学或算法的方法可以做到这一点。是否有替代方法:
# s = satellite, t = target
if pos == \"top\" && align == \"left\"
  s.x = t.x
  s.y = t.y - s.height
else if pos == \"top\" && align == \"center\"
  s.x = t.x + t.width / 2 - s.width / 2
  s.y = t.y - s.height
# etc, etc
Ruby或JavaScript有什么好的解决方案吗?     
已邀请:
我喜欢其他答案,但这是无需存储任何内容的方法。应用算术运算符时,使用javascript
true
计算为1和and4ѭ计算为0的技巧的所有数学和逻辑: ps。 (查看有效的jsfiddle:http://jsfiddle.net/vQqSe/52/)
var t = {
    jq: $(\'#target\'),
    width: parseInt($(\'#target\').css(\'width\')),
    height: parseInt($(\'#target\').css(\'height\')),
    top: parseInt($(\'#target\').css(\'top\')),
    left: parseInt($(\'#target\').css(\'left\'))
};
var s = {
    jq: $(\'#satellite\'),
    width: parseInt($(\'#satellite\').css(\'width\')),
    height: parseInt($(\'#satellite\').css(\'height\'))
};

// start with it top left and add using javascript tricks
s.jq.css(\'top\', t.top - s.height +
    s.height * (a == \'top\') +
    (t.height/2 + s.height/2) * (a == \'middle\') +
    t.height * (a == \'bottom\') +
    (t.height + s.height) * (p == \'bottom\')
);        

s.jq.css(\'left\', t.left - s.width +
    t.width * (a == \'left\') +
    s.width * (a == \'right\') +
    (s.width/2 + t.width/2) * (a == \'center\') +
    (s.width + t.width) * (p == \'right\')
);
    
如果使用了一系列对象,它将达到目的: var position = {     顶部:{左:{x:t​​.x,y:y.y-s.height},居中:{x:t​​x.x + t.width / 2- s.width / 2,y:t.y-s.height}}     //等等.... } //然后获取位置即可 var pos = positions [pos] [align])     
def vector pos, align, hash
  case hash[pos]
  when -1;     [0.0, -1.0]
  when 1;      [1.0, 0.0]
  else
    case hash[align]
    when -1;   [0.0, 0.0]
    when 1;    [1.0, -1.0]
    else       [0.5, -0.5]
    end
  end
end

y_t, y_s = vector(pos, align, \"top\" => -1, \"bottom\" => 1)
x_t, x_s = vector(pos, align, \"left\" => -1, \"right\" => 1)
s.y = t.y + y_t*t.height + y_s*s.height
s.x = t.x + x_t*t.width + x_s*s.width
要么
def vector pos, align, head, tail
  case pos
  when head;   [0.0, -1.0]
  when tail;   [1.0, 0.0]
  else
    case align
    when head; [0.0, 0.0]
    when tail; [1.0, -1.0]
    else       [0.5, -0.5]
    end
  end
end

y_t, y_s = vector(pos, align, \"top\", \"bottom\")
x_t, x_s = vector(pos, align, \"left\", \"right\")
s.y = t.y + y_t*t.height + y_s*s.height
s.x = t.x + x_t*t.width + x_s*s.width
    

要回复问题请先登录注册