隐藏元素的宽高无法通过原生js获取的问题

时间:2022-02-09 23:51:27

1、起源:移动app项目中,页面加载时需要加载国家下拉列表,将隐藏的透明浮层和一个显示加载过程中的框 显示出来,隐藏的透明浮层设置宽高都是100%即可,而这个加载提示框需要先得出它的宽高,然后再根据页面的宽高计算它的绝对定位的left和top

隐藏元素的宽高无法通过原生js获取的问题

2、用js获取该元素的宽高,结果都是0,该元素的css代码如下,因为display:none隐藏元素不占位置,所以宽高都为0,而用jQuery$("#loadImg").height()能获取到,通过网上查资料,是说jquery的这种获取方式是通过先把隐藏元素克隆一份,放置在这个元素相同的父元素里面,然后用display:block来显示元素,用绝对定位position:absolute来脱离文档流,设置top为负值,这样不会影响原先的元素,这样js获取宽高后再把它删掉。

#loadImg{width:70%; background:#000; border-radius:5px; color:#fff; line-height:35px; text-align:center; opacity:0.7; z-index:; display:none; border-:5px; padding:10px;}
var ew=document.getElementById("loadImg").style.offsetWidth;
var eh=document.getElementById("loadImg").style.offsetHeight; // 0 0

3、方法如下,为什么放在相同的父元素下,因为css样式有些是有父元素的,如果放在body里面,宽高属性没加载上的话 ,也获取不了。


var loadImg=document.getElementById("loadImg")
getDomWidthOrHeight("width",loadImg)
getDomWidthOrHeight("height",loadImg)
// 100   200

/**
* 获取隐藏元素的宽 高
* @param {Object} obj
*/
function getDomWidthOrHeight(widthOrHeight,obj){
//console.log(widthOrHeight+"="+obj);
var clone=obj.cloneNode(true);
clone.style.display="block";
clone.style.position="absolute";
  clone.style.top=-10000px;
   obj.parentNode.appendChild(clone);

    var width=clone.offsetWidth;
var height=clone.offsetHeight;
//console.log(width+"--"+height);
obj.parentNode.removeChild(clone);
return widthOrHeight=="width"?width:height;
}