Js determines how to obtain the actual width and height of an image after the image is loaded. js Load
This article describes how to obtain the actual width and height of an image after js judges that the image is loaded. We will share this with you for your reference. The details are as follows:
Normally, we use jq. width ()/. the height () method is used to obtain the width/height of an image or js. offsetwidth /. the offsetheight method is used to obtain the width and height of an image. However, after we set the width and height of an image through a style, the actual width and height of the image are not obtained, this is obviously not the expected result in some cases. Is there a way to obtain the actual width and height? The answer is yes. The following code can solve this problem:
Js code:
// Obtain the actual width and height of the image after the image is loaded. var _ test = document. getElementById ("test"); test. onload = function () {imgSize. call (_ test);} function imgSize () {var imgObj = new Image (); imgObj. src = this. src; alert (imgObj. width + "\ n" + imgObj. height );}
If you want to call this actual width and height in other methods, you should set alert (imgObj. width + "\ n" + imgObj. height); change to return imgObj, and then call the method:
window.onload = function(){ function a(){ var real= imgSize.call(_test); var realwidth = real.width; alert(realwidth); } a();}
The above method is too cumbersome and has been refined by myself. It is abbreviated as follows:
Window. onload = function () {var _ test = document. getElementById ("test"); // If jq is used, replace the Code with var _ test =$ ("# test. Var imgObj = new Image (); imgObj. src = _ test. src; // If jq is used, replace the Code with imgObj. src = _ test. attr ("src. Alert (imgObj. width );}
In this way, you can directly call the actual width and height of the image in other methods.