Duang~这个方法:Element.getBoundingClientRect 你熟悉吗?
七娃博客682人阅读
第一眼看到这个属性的时候,突然想到微信小程序获取右上角胶囊的方法:wx.getMenuButtonBoundingClientRect(),发现二者单词都很接近,所以猜到是获取元素的位置属性的方法。查询mdn之后,果真如下:
Element.getBoundingClientRect
返回一个DOMRect对象,包含元素的宽高、坐标位置及上下左右间距属性。
DOMRect{ bottom: 160 height: 80 left: 468.5 right: 668.5 top: 80 width: 200 x: 468.5 y: 80 }
使用方法:
let box = document.getElementsByClassName("box")[0] console.log(box.getBoundingClientRect()) //返回上面domrect对象 console.log(box.getBoundingClientRect().top) // 80 console.log(box.getBoundingClientRect().x) // 468.5
兼容性
ie都支持这个方法,其他浏览器就不用说了,不过ie返回的数据没有坐标x,y轴属性,需要兼容ie的需要注意,特别使用这个坐标属性的。
评论 | 0 条评论
登录之后才可留言,前往登录