如何使用 JavaScript 检测元素重叠(重叠)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5720837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect elements overlapping (overlaying) using JavaScript?
提问by Feniks502
How to detect overlap HTML elements, using JavaScript?
如何使用 JavaScript 检测重叠的 HTML 元素?
I have an item list (<ul>
). It slides up and down using JavaScript. When it slides down, depending on number of item, it may overlap the other element (<div>
), which is absolute positioned at this time (it can be changed).
我有一个项目列表 ( <ul>
)。它使用 JavaScript 上下滑动。当它向下滑动时,根据项目的数量,它可能会与另一个元素(<div>
)重叠,此时是绝对定位(可以更改)。
How I can detect, when <ul>
overlaps this <div>
, to apply new style to the <div>
to hide it temporary or to move it down a little bit, to prevent overlapping?
It's just not looking good, when they overlap))
我如何检测,当<ul>
与 this 重叠时<div>
,将新样式应用于<div>
以暂时隐藏它或将其向下移动一点,以防止重叠?
当它们重叠时,它看起来并不好))
Here you can see, what I'm talking about: http://timetable.raj.fvds.ru/
在这里你可以看到,我在说什么:http: //timetable.raj.fvds.ru/
Thanks a lot!
非常感谢!
回答by ChrisThompson
function isObjOnObj(a,b){
var al = a.left;
var ar = a.left+a.width;
var bl = b.left;
var br = b.left+b.width;
var at = a.top;
var ab = a.top+a.height;
var bt = b.top;
var bb = b.top+b.height;
if(bl>ar || br<al){return false;}//overlap not possible
if(bt>ab || bb<at){return false;}//overlap not possible
if(bl>al && bl<ar){return true;}
if(br>al && br<ar){return true;}
if(bt>at && bt<ab){return true;}
if(bb>at && bb<ab){return true;}
return false;
}
回答by oblig
This feels like collision detection, and there's a solution just posted. Instead, I would suggest working out how many list items would be needed for a menu to overlap (i.e. 10), and hide the div
when those menus (with 10 li
) are selected.
这感觉就像碰撞检测,刚刚发布了一个解决方案。相反,我建议计算出一个菜单重叠(即 10 个)需要多少个列表项,并在div
选择这些菜单(10 个li
)时隐藏它们。
回答by Mark Kahn
Why not just raise the z-index of your UL to be above the div at the bottom?
为什么不将 UL 的 z-index 提高到底部的 div 之上?
add:
添加:
#wrap {
z-index : 2;
position : relative;
}