gpt4 book ai didi

javascript - 放置两个矩形的优雅方式

转载 作者:数据小太阳 更新时间:2023-10-29 05:36:58 27 4
gpt4 key购买 nike

我有一个矩形(称为目标)并想在旁边放置另一个矩形(称为卫星)。卫星具有确定相对于目标的放置边缘的位置(顶部、底部、左侧、右侧)。它还有一个对齐方式(左、中、右用于顶部和底部位置,顶部、中间和底部用于左侧和右侧位置)。

例子:

+----------+----------------------------+
| | |
| 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 和 false 计算结果为 0 的技巧:

附注(查看工作中的 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')
);

关于javascript - 放置两个矩形的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com