我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?
当前回答
仅限Javascript:)
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
其他回答
我改编了这个简短的jQuery函数扩展,你可以自由使用(MIT许可)。
/**
* returns true if an element is visible, with decent performance
* @param [scope] scope of the render-window instance; default: window
* @returns {boolean}
*/
jQuery.fn.isOnScreen = function(scope){
var element = this;
if(!element){
return;
}
var target = $(element);
if(target.is(':visible') == false){
return false;
}
scope = $(scope || window);
var top = scope.scrollTop();
var bot = top + scope.height();
var elTop = target.offset().top;
var elBot = elTop + target.height();
return ((elBot <= bot) && (elTop >= top));
};
唯一的插件一直为我做这件事,是:https://github.com/customd/jquery-visible
我最近将这个插件移植到GWT,因为我不想仅仅为了使用这个插件而添加jquery作为依赖。下面是我的(简单的)端口(只包括我用例所需的功能):
public static boolean isVisible(Element e)
{
//vp = viewPort, b = bottom, l = left, t = top, r = right
int vpWidth = Window.getClientWidth();
int vpHeight = Window.getClientHeight();
boolean tViz = ( e.getAbsoluteTop() >= 0 && e.getAbsoluteTop()< vpHeight);
boolean bViz = (e.getAbsoluteBottom() > 0 && e.getAbsoluteBottom() <= vpHeight);
boolean lViz = (e.getAbsoluteLeft() >= 0 && e.getAbsoluteLeft() < vpWidth);
boolean rViz = (e.getAbsoluteRight() > 0 && e.getAbsoluteRight() <= vpWidth);
boolean vVisible = tViz && bViz;
boolean hVisible = lViz && rViz;
return hVisible && vVisible;
}
我添加了我的代码修改。不幸的是,我可以看到每个人都在他们的版本,每个人都忽略了debance功能的使用。哪个答案是让你的事件不触发,例如,在滚动时每秒200次。
$(window).scroll(function(){
if (isInView($('.class'))){
debounce(
someFunction(), 5
)
}
});
function isInView(elem){
if(document.documentElement.clientWidth > 991){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
}else {
doSometing;
}
}
在打印稿
private readonly isElementInViewPort = (el: HTMLElement): boolean => {
const rect = el.getBoundingClientRect();
const elementTop = rect.top;
const elementBottom = rect.bottom;
const scrollPosition = el?.scrollTop || document.body.scrollTop;
return (
elementBottom >= 0 &&
elementTop <= document.documentElement.clientHeight &&
elementTop + rect.height > elementTop &&
elementTop <= elementBottom &&
elementTop >= scrollPosition
);
};
在这个伟大答案的基础上,你可以使用ES2015+进一步简化它:
function isScrolledIntoView(el) {
const { top, bottom } = el.getBoundingClientRect()
return top >= 0 && bottom <= window.innerHeight
}
如果你不关心顶部是否跳出窗口而只关心底部是否被看到,这可以简化为
function isSeen(el) {
return el.getBoundingClientRect().bottom <= window.innerHeight
}
或者甚至是单行语句
const isSeen = el => el.getBoundingClientRect().bottom <= window.innerHeight