el.offsetTop - document.documentElement.scrollTop <= viewPortHeight
代码实现:
function isInViewPortOfOne (el) {
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
const offsetTop = el.offsetTop
const scrollTop = document.documentElement.scrollTop
const top = offsetTop - scrollTop
return top <= viewPortHeight
function isInViewPort(element) {
const viewWidth = window.innerWidth || document.documentElement.clientWidth;
const viewHeight = window.innerHeight || document.documentElement.clientHeight;
const {
top,
right,
bottom,
left,
} = element.getBoundingClientRect();
return (
top >= 0 &&
left >= 0 &&
right <= viewWidth &&
bottom <= viewHeight
);
}
const options = {
threshold: 1.0,
root:document.querySelector('#scrollArea')
};
const callback = (entries, observer) => { ....}
const observer = new IntersectionObserver(callback, options);
const callback = function(entries, observer) {
entries.forEach(entry => {
entry.time;
entry.rootBounds;
entry.boundingClientRect;
entry.intersectionRect;
entry.intersectionRatio;
entry.target;
});
};
const target = document.querySelector('.target');
observer.observe(target);
const observer = new IntersectionObserver(getYellow, { threshold: 1.0 });
getYellow回调函数实现对背景颜色改变,如下:
function getYellow(entries, observer) {
entries.forEach(entry => {
$(entry.target).css("background-color", "yellow");
});
}
最后传入观察者,即.target元素
observer.observe(element);