根据浏览器边缘的距离定位 div (javascript)

发布于 2024-07-13 06:02:35 字数 227 浏览 8 评论 0原文

我正在尝试创建一个主要依赖于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫性小仙女 2024-07-20 06:02:35

我只需要自己编写非常相似的代码,与 tipsy 一起使用(所以我的解决方案使用 jQuery )。 这是基本的数学计算,假设

...

是您正在使用的 div。 在测量到右边缘和下边缘的距离时,我也会考虑 div 的高度和宽度。

dTopdBottomdLeftdRight 是距 div 顶部、底部、左侧和右侧的距离边缘,分别到视口的同一边缘。 如果要根据div的左上角进行测量,在计算dBottom时不要减去dTopdLeft >d对

var $doc = $(document),
    $win = $(window),
    $this = $('#mydiv'),
    offset = $this.offset(),
    dTop = offset.top - $doc.scrollTop(),
    dBottom = $win.height() - dTop - $this.height(),
    dLeft = offset.left - $doc.scrollLeft(),
    dRight = $win.width() - dLeft - $this.width();

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, and dRight 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 subtract dTop or dLeft when computing dBottom and dRight.

var $doc = $(document),
    $win = $(window),
    $this = $('#mydiv'),
    offset = $this.offset(),
    dTop = offset.top - $doc.scrollTop(),
    dBottom = $win.height() - dTop - $this.height(),
    dLeft = offset.left - $doc.scrollLeft(),
    dRight = $win.width() - dLeft - $this.width();
疏忽 2024-07-20 06:02:35

备忘单用于原型库 有一个很好的例子。

This cheat sheet for the Prototype library has a good example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文