移动端如何准确获取元素真实的宽高度,精确到小数点后两位
获取元素的高度方法:
元素有个方法 offsetHeight 可以来获取元素高度
缺陷
使用offsetHeight会有一个问题,就是offsetHeight的高度会被四舍五入成一个整数,也就是说会丢失元素的高度精度
元素的实际高度为18.77px
而offsetHeight给出的高度为19px
如果在面对一些业务场景中需要不丢失精度的获取元素的高度,那么用offsetHeight来获取元素高度就不可行了
解决方案
使用 getComputedStyle() 方法来获取准确的元素高度
var items = this.refs.swiper.children //获取元素的节点
let height = window.getComputedStyle(items[0],null).height //得到 18.7656px
let num = parseFloat(height.substring(0,height.indexOf('px'))); // 得到18.7656
return num.toFixed(2) //得到18.77
getComputedStyle(element[,pseudo-element]) 有两个参数一个是元素一个是伪类,伪类可不用传
返回的对象是 CSSStyleDeclaration 类型的对象
根据需求去取对应的属性值即可
这样就可以获取到不丢失精度的元素高度或者宽度啦~
以下为window.getComputedStyle(items[0],null) 方法返回的属性