快速获取dom到body左侧和顶部的距离,简单粗暴无bug-getBoundingClientRect
获取dom到body左侧和顶部的距离-getBoundingClientRect 平时在写js的时候,偶尔会需要用js来获取当前div到 body 左侧、顶部的距离。网上查一查,有很多都是通过offsetTop、offsetLeft来计算出来的。我按照网上的查到的资料用了一次,算出来了一堆错误答案。 下面我要分享的这个方法,兼容性很好(ie4都ok),而且很方便,不会算错。 这个方法就是 getBoundingClientRect。 1.getBoundingClientRect方法简介 getBoundingClientRect 返回的是一个 DOMRect 对象,是一组矩形集合,我们这次所使用的返回值主要是left、top、bottom和right。其余的返回值width、height、x、y这次用不到,就不再讨论。 使用方法如下: let domToTop = dom.getBoundingClientRect().top // dom 的顶边到视口顶部的距离 let domToLeft = dom.getBoundingClientRect().left // dom 的左边到视口左边的距离 let domToBottom = dom.getBoundingClientRect().bottom // dom 的底边到视口顶部的距离 let domToRight = dom