我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?
当前回答
我添加了我的代码修改。不幸的是,我可以看到每个人都在他们的版本,每个人都忽略了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;
}
}
其他回答
我添加了我的代码修改。不幸的是,我可以看到每个人都在他们的版本,每个人都忽略了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;
}
}
我改编了这个简短的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));
};
我需要检查可滚动DIV容器内元素的可见性
//p = DIV container scrollable
//e = element
function visible_in_container(p, e) {
var z = p.getBoundingClientRect();
var r = e.getBoundingClientRect();
// Check style visiblilty and off-limits
return e.style.opacity > 0 && e.style.display !== 'none' &&
e.style.visibility !== 'hidden' &&
!(r.top > z.bottom || r.bottom < z.top ||
r.left > z.right || r.right < z.left);
}
简单的检查元素(el)是否在可滚动的div (holder)中可见
function isElementVisible (el, holder) {
holder = holder || document.body
const { top, bottom, height } = el.getBoundingClientRect()
const holderRect = holder.getBoundingClientRect()
return top <= holderRect.top
? holderRect.top - top <= height
: bottom - holderRect.bottom <= height
}
使用jQuery:
var el = $('tr:last').get(0);
var holder = $('table').get(0);
var isVisible = isElementVisible(el, holder);
如果你想在另一个div中滚动项目,
function isScrolledIntoView (elem, divID)
{
var docViewTop = $('#' + divID).scrollTop();
var docViewBottom = docViewTop + $('#' + divID).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
推荐文章
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 使用jQuery滚动到一个div
- 在JS/jQuery中触发按键/按键/按键事件?