如何在JavaScript中检测元素何时超过另一个元素? [英] How to detect when an element over another element in JavaScript?
本文介绍了如何在JavaScript中检测元素何时超过另一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了大部分代码......当元素完全覆盖其他元素时,它就可以工作了。问题是,当元素完全在元素上时,我不仅仅希望它是真的,当元素部分地超过另一个元素时,我也希望它是真的。
I wrote most of the code... And when the element is "fully" over the other element it works. The problem is that I don't just want it to be true when the element is "fully" over the element, I also want it to be true when the element is partly over the other element.
这是我的代码:
element = this.element.getStyles('left', 'top', 'width', 'height');
elementLeftX = element.left.toInt();
elementLeftY = element.top.toInt();
elementRightX = (element.width.toInt() + element.left.toInt());
elementRightY = (element.top.toInt() + element.height.toInt());
el = this.positions ? this.positions[i] : this.getDroppableCoordinates(el); // Element drop area
elLeftX = el.left.toInt();
elLeftY = el.top.toInt();
elRightX = (el.width.toInt() + el.left.toInt());
elRightY = (el.height.toInt() + el.top.toInt());
if (((elLeftY <= elementLeftY) && (elementLeftY <= elRightY)) && ((elLeftY <= elementRightY) && (elementRightY <= elRightY))) {
if (((elLeftX <= elementLeftX) && (elementLeftX <= elRightX)) && ((elLeftX <= elementRightX) && (elementRightX <= elRightX))) {
return true;
} else {
return false;
}
} else {
return false;
}
我很困惑,我已经玩了一段时间而且我只是无法让它发挥作用。
I am very confused and I have been playing around for a while and I just can't get it to work.
推荐答案
标准视频游戏方法:
doElsCollide = function(el1, el2) {
el1.offsetBottom = el1.offsetTop + el1.offsetHeight;
el1.offsetRight = el1.offsetLeft + el1.offsetWidth;
el2.offsetBottom = el2.offsetTop + el2.offsetHeight;
el2.offsetRight = el2.offsetLeft + el2.offsetWidth;
return !((el1.offsetBottom < el2.offsetTop) ||
(el1.offsetTop > el2.offsetBottom) ||
(el1.offsetRight < el2.offsetLeft) ||
(el1.offsetLeft > el2.offsetRight))
};
这篇关于如何在JavaScript中检测元素何时超过另一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文