为了计算一个元素是否可见,你可以创建这样一个函数(信用在这里https://stackoverflow.com/a/22480938/825240):
function isScrolledIntoView(element) {
var elementTop = element.getBoundingRect().top;
var elementBottom = element.getBoundingRect().bottom;
var isVisible = (elementTop <= window.innerHeight) && (elementBottom >= 0);
return isVisible;
}
您可以通过计算是否已读取元素来根据您的情况自定义该函数:
function isRead(element) {
var elementTop = element.getBoundingRect().top;
var elementBottom = element.getBoundingRect().bottom;
var elementHeight = elementBottom - elementTop;
// if 75% of the document has been scrolled, we'll assume it's been read
var readIfPercentage = 0.75;
// an element has been read if the top has been scrolled up out of view
// and at least 75% of the element is no longer visible
var isRead = (elementTop < 0 && Math.abs(elementTop) / elementHeight >= readIfPercentage);
return isRead;
}
然后你可以调用上面的函数,传入一个 DOM 节点作为元素:
isScrolledIntoView(document.getElementById('targetDiv');
//or
isRead(document.getElementById('targetDiv');
您可以通过创建滚动侦听器将它们联系在一起(jQuery 使这非常容易):
function setScrollListener() {
var scrollEventHandler = function() {
if (isRead(document.getElementById('article'))) {
// set article to 'read'
}
}
// on scroll, fire the event handler
$(document).scroll(scrollEventHandler);
}
值得注意的是,如果你想解绑滚动监听,比如文章都读完了,不再需要监听滚动,可以在scrollEventHandler中调用解绑函数。它很简单:
function unbindScrollEventHandler() {
$(document).unbind('scroll', scrollEventHandler);
}