判斷元素是否在視區內
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; }