简体   繁体   中英

Vertically aligning dynamically loading images using jquery

I want to align images loading in a div dynamically . I have thought of a solution to get the height of the parent div and getting the height of the currently loading image and subtract this from the parent div and divide by 2 .. something like this ..

$(".gallery a").click(function (evt) {
      evt.preventDefault();
      $(".image").empty().append( 
      $("<img>", {src: this.href})
      );
    });

here i want to add something like this but i dont know the exact code

$("<img>", {src: this.href, style: (margin-top:350-src.height()/2})

where 350 is say my parent div height .. please give me a code for this .. i have tried everything but nothing else works on these dynamically loading images.

'mydesirednumber' variable in the code I posted below, contains the answer to your "get the height of the parent div and getting the height of the currently loading image and subtract this from the parent div and divide by 2 "

Below example assumes you have DOM structure like this:

GALLERY
  - DIV CLASS="thatdiv"
     -IMAGE
     -IMAGE
     -IMAGE
  - A (anchor)
  - A (another anchor)...

Code is below:

$(".gallery a").click(function (evt) {
      evt.preventDefault();
      //whatever else you wanted to do before, here
      var parentdivheight = $('.thatdiv').height();
      var imageheight = $(<<WHEREVER-CURRENTLYLOADING-IMAGE-IS>>).height();
      var mydesirednumber = (parentdivheight - imageheight)  /2 ;
       //whatever else you wanted to do after, here

    });

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