我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?
当前回答
WebResourcesDepot在前段时间使用jQuery编写了一个滚动加载脚本。你可以在这里查看他们的现场演示。它们功能的关键在于:
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastAddedLiveFunc();
}
});
function lastAddedLiveFunc() {
$('div#lastPostsLoader').html('<img src="images/bigLoader.gif">');
$.post("default.asp?action=getLastPosts&lastPostID="+$(".wrdLatest:last").attr("id"),
function(data){
if (data != "") {
$(".wrdLatest:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
其他回答
唯一适用于我的解决方案是(当$("#elementToCheck")可见时返回true):
$ (document) .scrollTop () + window.innerHeight + $ (" # elementToCheck ") .height () > $ (" # elementToCheck ") .offset直()上
用香草语回答:
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
// Only completely visible elements return true:
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
//isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
}
使用IntersectionObserver API
(在现代浏览器中本机)
通过使用观察器来确定一个元素在视口中是否可见,或者在任何可滚动的容器中是否可见,这是非常简单有效的。
无需附加滚动事件并手动检查事件回调,这更有效:
//定义一个观察者实例 var观察者= new IntersectionObserver(onIntersection, { Root: null, // default为视口 阈值:目标可见区域的。5 //百分比。触发“onIntersection” }) //在交集变化时调用回调函数 函数onIntersection(条目,opts){ 条目。forEach(入口= > entry.target.classList。切换(“可见”,entry.isIntersecting) ) } //使用观察者来观察一个元素 观察者。观察(document.querySelector('.box')) //停止观察: / / observer.unobserve (entry.target) 跨度{:固定;上图:0;左:0;} .box{宽度:100 px;身高:100 px;背景:红色;保证金:1000 px;过渡:综合成绩;} .box。可见{背景:绿色;这个特性:50%;} <span>纵向滚动&水平…< / span > < div class = '盒子' > < / div >
现代浏览器(包括移动浏览器)支持。IE - View浏览器支持表中不支持
WebResourcesDepot在前段时间使用jQuery编写了一个滚动加载脚本。你可以在这里查看他们的现场演示。它们功能的关键在于:
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastAddedLiveFunc();
}
});
function lastAddedLiveFunc() {
$('div#lastPostsLoader').html('<img src="images/bigLoader.gif">');
$.post("default.asp?action=getLastPosts&lastPostID="+$(".wrdLatest:last").attr("id"),
function(data){
if (data != "") {
$(".wrdLatest:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
唯一的插件一直为我做这件事,是: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;
}