admin管理员组文章数量:1357112
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
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
Share Improve this question edited Feb 2, 2009 at 17:25 Diodeus - James MacFarlane 114k33 gold badges163 silver badges180 bronze badges asked Feb 2, 2009 at 17:12 CawlinCawlin 2194 silver badges7 bronze badges3 Answers
Reset to default 5I 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 puting 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();
See Measuring Element Dimension and Location for help
This cheat sheet for the Prototype library has a good example.
本文标签: positioningPosition div depending on distance browser edge (javascript)Stack Overflow
版权声明:本文标题:positioning - Position div depending on distance browser edge (javascript) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744074407a2586476.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论