开发者

How do I use jQuery to determine when a div is out of view to the right?

开发者 https://www.devze.com 2023-03-15 20:54 出处:网络
I have a div that displays near a control when it\'s focused on.Initially, the div was on the left of the control, and life was easy.A simple if left < 0 { left = 0; } would keep the div on the scr

I have a div that displays near a control when it's focused on. Initially, the div was on the left of the control, and life was easy. A simple if left < 0 { left = 0; } would keep the div on the screen. Now the div needs to be on the righ开发者_JAVA百科t, and I can't figure out a similar bit of code. Also, the code needs to determine not only if it's off-screen to the right, but also if it's past the visibility of a (possible) scrollable containing div. How can I accomplish this? Assume the scrollable div, if applicable, can be found with $('.PanelScroll') and we can call the div needing placement elem.


This is more of the simple solution I was looking for:

var ctrl = $('#<your control id>');         // This is the control that the div is display to the right of.
var elem = $('#<your element id>');         // This is the div that may be out of view.
var panel = $('#<your scrollable div id>');
var left = elem.position().left;
var right = left + elem.outerWidth();

if ((panel.length && (right > panel.innerWidth())) || (right > ($(window).width() + $(window).scrollLeft()))) {
    left = left - ctrl.outerWidth() - elem.outerWidth();
}

if (panel.length) {
    left += panel.scrollLeft();
}

elem.css('left', left);
0

精彩评论

暂无评论...
验证码 换一张
取 消