如何在滚动后检查元素是否可见? [英] How to Check if element is visible after scrolling?
本文介绍了如何在滚动后检查元素是否可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过AJAX加载元素。只有当你向下滚动页面时,其中一些才会显示。
有什么方法我可以知道元素现在是否在页面的可见部分?
I'm loading elements via AJAX. Some of them are only visible if you scroll down the page.
Is there any way I can know if an element is now in the visible part of the page?
推荐答案
这应该可以解决问题:
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
简单实用功能
这将允许您调用一个实用程序函数,该函数接受您正在查找的元素,以及您是否希望元素完全处于视图中或部分查看。
Simple Utility Function This will allow you to call a utility function that accepts the element you're looking for and if you want the element to be fully in view or partially.
function Utils() {
}
Utils.prototype = {
constructor: Utils,
isElementInView: function (element, fullyInView) {
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height();
var elementTop = $(element).offset().top;
var elementBottom = elementTop + $(element).height();
if (fullyInView === true) {
return ((pageTop < elementTop) && (pageBottom > elementBottom));
} else {
return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
}
}
};
var Utils = new Utils();
用法
var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);
if (isElementInView) {
console.log('in view');
} else {
console.log('out of view');
}
这篇关于如何在滚动后检查元素是否可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文