简体   繁体   中英

Does changing an img src attribute emit any emitters?

I am working on a page which has images of varying sizes, and I want to change the parent div size in accordance to the new image's height.

I have inner , viewOne and viewTwo set as global variables, and my code is as follows.

  viewOne.src = 'path/to/newImage.png';
  viewTwo.src = 'path/to/otherImage.png';

  inner = document.getElementById('innerWindow'); // Parent Div
  viewOne = document.getElementById('viewImgOne'); // Image Object
  viewTwo = document.getElementById('viewImgTwo'); // Image Object

  if(viewOne.clientHeight >= viewTwo.clientHeight) {
    inner.style.height = viewOne.clientHeight + "px";
  } else {
    inner.style.height = viewTwo.clientHeight + "px";
  };

The parent div doesn't always resize itself properly after changing image paths, so there might be a few hundred pixels left over in the bottom of the div that shouldn't be there at time.

I also have a window.onresize function to resize the div if the browser window changes, and it works as intended.

Is there a way to watch src , and run the resize function after the image fully loads?

One approach to this problem is to bind the .load event for all images and then you will know when the image has finished loading, after a src change. I'm not sure if there is a more direct way to observe src changes. However, for this to work consistently, you need to bind .load before anything touches the image element's .src.

If you are creating the image elements dynamically that shouldn't be a problem, or if you are re-using the same image tags over and over that shouldn't be an issue (besides for the initial first load on page load, but you probably don't need to worry about that?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM