判斷元素是否在視口和元素相交

看風景就發表於2018-05-21

判斷元素是否在視區內

function isElementInViewport (el) {
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

計算兩個元素的相交面積

function getIntersect(rect1,rect2){
    var minx = Math.max(rect1.left,rect2.left),
        miny = Math.max(rect1.top,rect2.top),
        maxx = Math.min(rect1.right,rect2.right),
        maxy = Math.min(rect1.bottom,rect2.bottom);
    if(minx > maxx || miny > maxy){
            return 0;
    }
    var deltaW= maxx - minx,
        deltaH = maxy - miny;

    return deltaW * deltaH;
}

 

相關文章