lynxerzhang / JSSkills

MIT License
0 stars 0 forks source link

利用getBoundingClientRect判断元素是否在窗口可视范围内 #3

Open lynxerzhang opened 6 years ago

lynxerzhang commented 6 years ago
// getBoundingClientRect 方法返回元素的边界,
// window的innerWidth和innerHeight返回当前窗口的实际长宽,不包括标题栏地址栏
var isVisibleInViewport = (function(){
    return function(element, inInsideWindow) {
        var rect = element.getBoundingClientRect();
        var innerWidth = window.innerWidth;
        var innerHeight = window.innerHeight;
        var top = rect.top;
        var left = rect.left;
        var right = rect.right;
        var bottom = rect.bottom;
        if(!inInsideWindow){
            inInsideWindow = false;
        }
        var isInside = false;
        if(inInsideWindow){
            isInside = top >= 0 && left >= 0 && 
                        right <= innerWidth && bottom <= innerHeight;
        }else{
            isInside = ((top >= 0 && top < innerHeight) || 
                            (bottom > 0 && bottom <= innerHeight)) && 
                        ((left >= 0 && left < innerWidth) || 
                            (right > 0 && right <= innerWidth));
        }
        return isInside;
    }
})();