6

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

4

3 回答 3

5

我只需要自己编写非常相似的代码,用于tipsy(所以我的解决方案使用jQuery)。这是基本的数学,假设<div id="mydiv">...</div>是你正在使用的 div。在测量到右边缘和下边缘的距离时,我也会考虑 div 的高度和宽度。

dTop, dBottom, dLeft, 和dRight分别是从 div 的顶部、底部、左侧和右侧边缘到视口同一边缘的距离。如果要根据 div 的左上角进行测量,计算and时不要减去dTopor 。dLeftdBottomdRight

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();
于 2010-07-28T18:59:21.013 回答
1

See Measuring Element Dimension and Location for help

于 2009-02-02T17:17:25.930 回答
0

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

于 2009-02-02T17:27:33.023 回答