我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?
当前回答
使用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浏览器支持表中不支持
其他回答
这个答案的一个更有效的版本:
/**
* Is element within visible region of a scrollable container
* @param {HTMLElement} el - element to test
* @returns {boolean} true if within visible region, otherwise false
*/
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
return (rect.top >= 0) && (rect.bottom <= window.innerHeight);
}
在打印稿
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
);
};
推特斯科特道丁的酷功能为我的要求- 这是用来查找元素是否刚刚滚动到屏幕上,即它的上边缘。
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}
唯一适用于我的解决方案是(当$("#elementToCheck")可见时返回true):
$ (document) .scrollTop () + window.innerHeight + $ (" # elementToCheck ") .height () > $ (" # elementToCheck ") .offset直()上
我更喜欢使用jQuery expr
jQuery.extend(jQuery.expr[':'], {
inview: function (elem) {
var t = $(elem);
var offset = t.offset();
var win = $(window);
var winST = win.scrollTop();
var elHeight = t.outerHeight(true);
if ( offset.top > winST - elHeight && offset.top < winST + elHeight + win.height()) {
return true;
}
return false;
}
});
你可以这样用
$(".my-elem:inview"); //returns only element that is in view
$(".my-elem").is(":inview"); //check if element is in view
$(".my-elem:inview").length; //check how many elements are in view
你可以很容易地在滚动事件函数中添加这样的代码等,以检查它每次用户将滚动视图。