我在JavaScript中有一个可运行的底部函数,用于检测用户是否在底部滚动。但是,当用户的分辨率(例如Windows缩放比例)很奇怪或缩放时,就会出现问题。该功能不再起作用,无法检测到底部。
这就是我所做的:
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
this.props.getNewValues();
}
有办法避免这种情况吗?即使您不缩放,这对于在电视或类似设备上显示网站的人也不起作用(就像我的一个朋友一样)
谢谢
编辑:我将其应用于精确的元素上,我重复说我的解决方案除了通过缩放外,其余都是有效的。取消缩放会提供浮动值,使响应无法真正准确地显示(根据缩放比例,其差异为1到50像素)
答案 0 :(得分:1)
我使用了此功能(不能像别人写的那样获得荣誉-很抱歉,没有信用-很久以前)。也许您可以使它适应您的用例:
(function($) {
//CHECK SCROLLED INTO VIEW UTIL
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();
//END CHECK SCROLLED INTO VIEW UTIL
//USING THE ELEMENT IN VIEW UTIL
//this function tells what to do do when the element is or isnt in view.
//var inView = Utils.isElementInView(el, false); Where FALSE means the element doesnt need to be completely in view / TRUE would mean the element needs to be completely in view
function IsEInView(el) {
var inView = Utils.isElementInView(el, false);
if(inView) {
//console.log('in view');
} else {
//console.log('not in view');
}
};
//Check to make sure the element you want to be sure is visible is present on the page
var variableOfYourElement = $('#variableOfYourElement');
//if it is on this page run the function that checks to see if it is partially or fully in view
if( variableOfYourElement.length ) {
//run function on page load
IsEInView(variableOfYourElement);
//run function if the element scrolls into view
$(window).scroll(function(){
IsEInView(variableOfYourElement);
});
}
//END USING THE ELEMENT IN VIEW UTIL
})(jQuery);