1, the Origin: Mobile app project, the page load needs to load the country drop-down list, the hidden transparent floating layer and a display loading process of the box display, hidden transparent floating layer set width is 100%, and this load prompt box needs to get its wide height, Then it calculates the left and top of its absolute position based on the width of the page.
2, with JS to get the width of the element, the result is 0, the CSS code of the element is as follows, because the Display:none hidden elements do not occupy a position, so the width of the height is 0, and with jquery$ ("#loadImg"). Height () can be obtained, through the online search information, That's the way jquery is acquired by first cloning a hidden element, placing it in the same parent element as the element, and then using Display:block to display the element, using absolute positioning position:absolute to escape the flow of the document, setting top to a negative value, This will not affect the original element, so that JS gets a wide height and then delete it.
#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, the method is as follows, why placed under the same parent element, because some CSS style is a parent element, if placed inside the body, the width and height of the property is not loaded, also can not get.
var Loadimg=document.getelementbyid ("Loadimg")
getdomwidthorheight ("width",loadimg)
Getdomwidthorheight ("height", loadimg)
///+
/* * * Gets the width of the hidden element * @param {O bject} 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; }
The problem of the hidden element's wide height cannot be obtained by native JS