Ja gets the height of a picture and assigns it to div,. How can it be refreshed once before it appears?

clipboard.png
js first gets the height of a picture, and then assigns a value to the height of a div. Why is it displayed after refreshing? how to solve it? ask for the elder"s advice. Thank you!

Mar.10,2021

display

after refresh

I guess the process might be like this:

  1. visits the page for the first time and gets the width and height (but the picture hasn't been loaded yet, so it fails. )
  2. then the picture is loaded
  3. the cache for direct reading of images when you visit the page for the second time
  4. get the correct width and height

so, your acquisition of offsetHeight should be done after making sure that the image has been loaded.


clipboard.png

my js is at the bottom of the page. My younger brother, a rookie, will trouble the elder to take a look at it again.


can you see if your imgHeight is 0 when it doesn't work? It feels like when performing js, the picture is not loaded and has no height.

Image loading is non-blocking, and the entire execution process needs to be performed after img's onload (or window.onload).

Menu