jQuery 如何检查元素是否在屏幕外
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8897289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an element is off-screen
提问by Max
I need to check with jQuery if a DIV element is not falling off-screen. The elements are visible and displayed according CSS attributes, but they could be intentionally placed off-screen by:
如果 DIV 元素没有脱离屏幕,我需要检查 jQuery。这些元素是可见的并根据 CSS 属性显示,但它们可以通过以下方式有意放置在屏幕外:
position: absolute;
left: -1000px;
top: -1000px;
I could not use the jQuery :visible
selector as the element has a non-zero height and width.
我无法使用 jQuery:visible
选择器,因为该元素的高度和宽度不为零。
I am not doing anything fancy. This absolute position placement is the way my Ajaxframework implements the hide/show of some widgets.
我没有做任何花哨的事情。这种绝对位置放置是我的Ajax框架实现某些小部件隐藏/显示的方式。
回答by scurker
Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?
取决于您对“屏幕外”的定义。是在视口内,还是在您的页面定义的边界内?
Using Element.getBoundingClientRect()you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):
使用Element.getBoundingClientRect()您可以轻松检测您的元素是否在视口的边界内(即屏幕上或屏幕外):
jQuery.expr.filters.offscreen = function(el) {
var rect = el.getBoundingClientRect();
return (
(rect.x + rect.width) < 0
|| (rect.y + rect.height) < 0
|| (rect.x > window.innerWidth || rect.y > window.innerHeight)
);
};
You could then use that in several ways:
然后,您可以通过多种方式使用它:
// returns all elements that are offscreen
$(':offscreen');
// boolean returned if element is offscreen
$('div').is(':offscreen');
回答by Sam Sehnert
There's a jQuery plugin herewhich allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.
这里有一个jQuery 插件,它允许用户测试元素是否落在浏览器的可见视口内,同时考虑浏览器的滚动位置。
$('#element').visible();
You can also check for partial visibility:
您还可以检查部分可见性:
$('#element').visible( true);
One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.
一个缺点是它只适用于垂直定位/滚动,尽管在混合中添加水平定位应该很容易。
回答by Simon Hudin
No need for a plugin to check if outside of view port.
不需要插件来检查是否在视口之外。
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var d = $(document).scrollTop();
$.each($("div"),function(){
p = $(this).position();
//vertical
if (p.top > h + d || p.top > h - d){
console.log($(this))
}
//horizontal
if (p.left < 0 - $(this).width() || p.left > w){
console.log($(this))
}
});
回答by pie6k
Well... I've found some issues in every proposed solution here.
嗯...我在这里的每个提议的解决方案中都发现了一些问题。
- You should be able to choose if you want entire elementto be on screen or just any part of it
- Proposed solutions fails if element is higher/wider than windowand kinda coversbrowser window.
- 您应该能够选择是希望整个元素显示在屏幕上还是仅显示其中的任何部分
- 如果元素高于/宽于窗口并且有点覆盖浏览器窗口,则建议的解决方案失败。
Here is my solution that include jQuery
.fn
instance function and expression
. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.
这是我的解决方案,其中包括jQuery
.fn
实例函数和expression
. 我在我的函数中创建了比我所能创建的更多的变量,但是对于复杂的逻辑问题,我喜欢将它分成更小的、明确命名的部分。
I'm using getBoundingClientRect
method that returns element position relatively to the viewport so I don't need to care about scroll position
我正在使用getBoundingClientRect
相对于视口返回元素位置的方法,所以我不需要关心滚动位置
Useage:
用途:
$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false
Source:
来源:
$.fn.isOnScreen = function(partial){
//let's be sure we're checking only one element (in case function is called on set)
var t = $(this).first();
//we're using getBoundingClientRect to get position of element relative to viewport
//so we dont need to care about scroll position
var box = t[0].getBoundingClientRect();
//let's save window size
var win = {
h : $(window).height(),
w : $(window).width()
};
//now we check against edges of element
//firstly we check one axis
//for example we check if left edge of element is between left and right edge of scree (still might be above/below)
var topEdgeInRange = box.top >= 0 && box.top <= win.h;
var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;
var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
var rightEdgeInRange = box.right >= 0 && box.right <= win.w;
//here we check if element is bigger then window and 'covers' the screen in given axis
var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;
//now we check 2nd axis
var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
//now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;
return partial ? isPartiallyOnScreen : isEntirelyOnScreen;
};
$.expr.filters.onscreen = function(elem) {
return $(elem).isOnScreen(true);
};
$.expr.filters.entireonscreen = function(elem) {
return $(elem).isOnScreen(true);
};
回答by Gijs Roge
I created a small plugin that does this, and it has some flexible options (it also works when you resize the browser window).
我创建了一个执行此操作的小插件,它有一些灵活的选项(在调整浏览器窗口大小时也可以使用)。
回答by user5294803
- Get the distance from the top of the given element
- Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
Then all you have to do is subtract that from total document height
jQuery(function () { var documentHeight = jQuery(document).height(); var element = jQuery('#you-element'); var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true)); alert(distanceFromBottom) });
- 获取距给定元素顶部的距离
- 添加相同给定元素的高度。这将告诉您从屏幕顶部到给定元素末尾的总数。
然后你所要做的就是从总文档高度中减去它
jQuery(function () { var documentHeight = jQuery(document).height(); var element = jQuery('#you-element'); var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true)); alert(distanceFromBottom) });
回答by mukama
I know this is kind of late but this plugin should work. http://remysharp.com/2009/01/26/element-in-view-event-plugin/
我知道这有点晚了,但这个插件应该可以工作。http://remysharp.com/2009/01/26/element-in-view-event-plugin/
$('p.inview').bind('inview', function (event, visible) {
if (visible) {
$(this).text('You can see me!');
} else {
$(this).text('Hidden again');
}
回答by Troy Barlow
You could check the position of the div using $(div).position()
and check if the left and top margin properties are less than 0 :
您可以使用$(div).position()
检查div 的位置并检查 left 和 top margin 属性是否小于 0 :
if($(div).position().left < 0 && $(div).position().top < 0){
alert("off screen");
}