美文网首页
IntersectionObserver API 使用教程

IntersectionObserver API 使用教程

作者: __越过山丘__ | 来源:发表于2019-01-14 14:41 被阅读0次

http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html

判断元素是否在可视区域内:
方法一:

function isInSight(el) {
    const bound = el.getBoundingClientRect();
    const clientHeight = window.innerHeight;

    //如果只考虑向下滚动加载
    //const clientWidth = window.innerWeight;
    if ( (bound.top + bound.height) < 0 ){
         return true;
    } else {
         return false;
    }
}

window.addEventListener('scroll', function(){
    let obj = document.querySelector('.parent');
    console.log(isInSight(obj))
})

方法二:

var intersectionObserver = new IntersectionObserver(
    function (entries){
        // 如果不可见,就返回
        if ( entries[0].intersectionRatio <= 0 ){
             console.log('不可见')
        } else {
             console.log('可见')
        }
    }
)

//开始观察
intersectionObserver.observe(
    document.querySelector('.parent')
)

相关文章

网友评论

      本文标题:IntersectionObserver API 使用教程

      本文链接:https://www.haomeiwen.com/subject/ovoddqtx.html