Javascript 检查元素是否在屏幕上可见
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5353934/
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
Check if element is visible on screen
提问by Robert
Possible Duplicate:
jQuery - Check if element is visible after scroling
可能的重复:
jQuery - 检查元素在滚动后是否可见
I'm trying to determine if an element is visible on screen. In order to to this, I'm trying to find the element's vertical position using offsetTop, but the value returned is not correct. In this case, the element is not visible unless you scroll down. But despite of this, offsetTop returns a value of 618 when my screen height is 703, so according to offsetTop the element should be visible.
我正在尝试确定某个元素是否在屏幕上可见。为此,我尝试使用 offsetTop 查找元素的垂直位置,但返回的值不正确。在这种情况下,除非向下滚动,否则元素不可见。但尽管如此,当我的屏幕高度为 703 时,offsetTop 返回的值为 618,因此根据 offsetTop 元素应该是可见的。
The code I'm using looks like this:
我正在使用的代码如下所示:
function posY(obj)
{
var curtop = 0;
if( obj.offsetParent )
{
while(1)
{
curtop += obj.offsetTop;
if( !obj.offsetParent )
{
break;
}
obj = obj.offsetParent;
}
} else if( obj.y )
{
curtop += obj.y;
}
return curtop;
}
Thank you in advance!
先感谢您!
回答by Tokimon
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
--- 无耻的插件 ---
我已将此功能添加到我创建的库中
vanillajs-browser-helpers:https: //github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
--- -----------------------------
Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top poisiton. The function your using is ok and does the job, though its abit more complex ath it needs to.
BenM 说得好,您需要检测视口的高度 + 滚动位置以匹配您的最高位置。您使用的功能没问题并且可以完成工作,尽管它需要更复杂一些。
If you dont use jQuery
then the script would be something like this:
如果你不使用,jQuery
那么脚本将是这样的:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
使用jQuery要容易得多:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks wether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
这甚至提供了第二个参数。使用“可见”(或没有第二个参数),它会严格检查元素是否在屏幕上。如果将其设置为“above”,则当相关元素位于屏幕上或屏幕上方时,它将返回 true。
See in action: http://jsfiddle.net/RJX5N/2/
见实战:http: //jsfiddle.net/RJX5N/2/
I hope this answers your question.
我希望这回答了你的问题。
-- IMPROVED VERSION--
- 改良版 -
This is a lot shorter and should do it as well:
这要短得多,也应该这样做:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
用小提琴来证明它:http: //jsfiddle.net/t2L274ty/1/
And a version with threshold
and mode
included:
并与一个版本threshold
,并mode
包括:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
并用小提琴来证明它:http: //jsfiddle.net/t2L274ty/2/
回答by BenM
Could you use jQuery, since it's cross-browser compatible?
您可以使用 jQuery,因为它是跨浏览器兼容的吗?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
然后使用以下内容调用该函数:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };