如何使用 jQuery 来确定 div 何时不在右侧视图中?

发布于 2024-11-17 17:35:36 字数 287 浏览 2 评论 0原文

我有一个 div,当它聚焦时会显示在控件附近。最初,div 位于控件的左侧,生活很简单。一个简单的 if left < 0 { 左 = 0; } 会将 div 保留在屏幕上。现在 div 需要位于右侧,但我无法找出类似的代码。此外,代码不仅需要确定它是否在屏幕右侧,还需要确定它是否超出了(可能的)可滚动包含 div 的可见性。我怎样才能做到这一点?假设可以使用 $('.PanelScroll') 找到可滚动的 div(如果适用),我们可以调用需要放置的 div elem

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 right, 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

三月梨花 2024-11-24 17:35:36

这是我一直在寻找的更简单的解决方案:

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);

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