根据浏览器边缘的距离定位 div (javascript)
我正在尝试创建一个主要依赖于 css 的小工具提示脚本。 我不明白的 JavaScript 部分是如何根据 div 到浏览器边缘的距离来定位它。
当 div 出现时,我希望它检查它与顶部、底部、左侧和右侧的距离。 例如,如果没有足够的空间来显示工具提示链接上方的 div,则应将其放置在链接下方。
本质上,我希望 div “意识到”它的位置并知道去哪里以确保它可见。
谢谢
I am trying to create a small tooltip script that mostly relies on css. The bit of JavaScript I can't figure out is how to position the div based on its distance to the browsers edge.
When the div appears I would like it to check how close it is to the top, bottom, left and right. For example if there is not enough space to display the div above the tooltip link it should position it below the link.
Essentially I would like the div to be "aware" of its position and know where to go to make sure it is visible.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只需要自己编写非常相似的代码,与 tipsy 一起使用(所以我的解决方案使用 jQuery )。 这是基本的数学计算,假设
是您正在使用的 div。 在测量到右边缘和下边缘的距离时,我也会考虑 div 的高度和宽度。
dTop
、dBottom
、dLeft
和dRight
是距 div 顶部、底部、左侧和右侧的距离边缘,分别到视口的同一边缘。 如果要根据div的左上角进行测量,在计算dBottom
和时不要减去
。dTop
或dLeft
>d对I just had to write very similar code myself, for use with tipsy (so my solution uses jQuery). Here's the basic math, assuming
<div id="mydiv">...</div>
is the div you're working with. I account for the div's height and width when measuring the distances to the right and bottom edges as well.dTop
,dBottom
,dLeft
, anddRight
are the distance from the div's top, bottom, left, and right edges, respectively, to the same edge of the viewport. If you want to measure based on the upper-left corner of the div, don't subtractdTop
ordLeft
when computingdBottom
anddRight
.请参阅测量元素尺寸和位置获取帮助
See Measuring Element Dimension and Location for help
此备忘单用于原型库 有一个很好的例子。
This cheat sheet for the Prototype library has a good example.