Skip to content

[js] 第645天 写一个JS方法,判断元素是否在可视区域 #3461

@haizhilin2013

Description

@haizhilin2013
Collaborator

第645天 写一个JS方法,判断元素是否在可视区域

3+1官网

我也要出题

Activity

xujs0813

xujs0813 commented on Jan 20, 2021

@xujs0813
// 判断元素是否在视口中
function isEleVisible(ele){
    var {top, right, bottom, left} = ele.getBoundingClientRect()
    var w = window.innerWidth
    var h = window.innerHeight
    if(bottom < 0 || top > h){
        // y 轴方向
        return false
    }
    if(right < 0 || left > w){
        // x 轴方向
        return false
    }
    return true
}
fanerge

fanerge commented on Jan 22, 2021

@fanerge

使用 IntersectionObserver 实现,性能更好
IntersectionObserver

// 默认以 viewport 为观察容器
var intersectionObserver = new IntersectionObserver(function(entries) {
  // todo 如懒加载等

});
// start observing
intersectionObserver.observe(document.querySelector('#loadVideo'));
// 合适的时机停止监听
intersectionObserver.unobserve(document.querySelector('#loadVideo'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@fanerge@xujs0813

        Issue actions

          [js] 第645天 写一个JS方法,判断元素是否在可视区域 · Issue #3461 · haizlin/fe-interview