简体   繁体   English

在将图像加载到页面上之前,如何使用jQuery计算图像的宽度和高度?

[英]How do I calculate the width and height of an image with jQuery, before I load the image on a page?

I'm banging my head against the wall on this because I know I've done it before. 我在这上面撞墙,因为我知道我以前做过。 But this code won't work. 但是此代码无法正常工作。 Now, I know a lot of this is a mess because I'm trying to throw it together quickly (Make it work, make it right, make it fast, etc), but what about this is causing me so much pain and agony? 现在,我知道很多事情都是一团糟,因为我正试图将其快速拼凑在一起(使它正常工作,使其正确,使其快速运行等),但是那会给我带来如此多的痛苦和痛苦吗?

I have the following basic HTML: 我有以下基本HTML:

<div class="js-gallery force js-on">
  <h5>More Images &raquo;</h5>
  <a href="http://url/to/image1.jpg"><img src="http://url/to/image_thumb1.jpg" alt=""></a>
  <a href="http://url/to/image2.jpg"><img src="http://url/to/image_thumb2.jpg" alt=""></a>
  <a href="http://url/to/image3.jpg"><img src="http://url/to/image_thumb3.jpg" alt=""></a>
        etc...
</div>

And the following JS to intercept link clicks, create an object to maintain state through the mini gallery (next, previous, active, etc.), and calculate screen width/height so the image fits well. 然后下面的JS拦截链接点击,创建一个对象来维护迷你画廊的状态(下一个,上一个,活动等),并计算屏幕的宽度/高度,以使图像非常合适。 Should be SO simple: 应该是如此简单:

// Set up intialized variables
var overlay = $("<div class='gallery-overlay' id='gallery-overlay'></div>").hide().appendTo("body"),
  state = {},
  galleryNext = $("<a class='gallery-next' href='#'>Next</a>"),
  galleryPrev = $("<a class='gallery-prev' href='#'>Previous</a>"),
  gallery = $(".js-gallery");

gallery.addClass("js-on");

gallery.find("a").click( function (e) {
  e.preventDefault();
  state.gallery = $(this).parent(".js-gallery");
  thisHref = this.href;
  overlay.fadeIn( 200, function () { 
    buildGalleryOverlay( thisHref ); 
  });
  return false;
});

$("#gallery-overlay").live( "click", function (e) {
  overlay.fadeOut();
  overlay.find("#image-box").remove();
});

$("#image-box a").live( "click", function (e) {
  var imageBox = $("#image-box");
  imageBox.fadeOut().remove();
  buildGalleryOverlay( this.href );
  return false;
});

function buildGalleryOverlay( clickedHref ) {
  var ww = $(window).width(),
    wh = $(window).height(),
    imageBox = $("<div class='image-box' id='image-box'></div>").appendTo(overlay).show(),
    image = $("<img src='" + clickedHref + "' />"),
    iw, oldW,
    ih, oldH,
    overWidth, overHeight,
    allImages;

  window.console.log( imageBox );

  if ( !state.total ) {
    state.total = 0;
    state.images = [];
    allImages = $(state.gallery).find("a");
    $.each( allImages, function (index, value) {
      state.total += 1;
      state.images.push(value.href);
    });
  }

  state.active = state.images.indexOf( clickedHref );
  state.next = state.images[state.active + 1];
  state.prev = state.images[state.active - 1];

  image.appendTo(imageBox);
  window.console.log( image );
  iw = $(image).width();
  ih = $(image).height();

  // continued...

Right here is where the problem happens, because every so often a click on an image link will return 0 and 0 for the width and height. 问题就在这里发生,因为单击图像链接的每一次单击都会返回宽度0和高度0。 No idea why. 不知道为什么。 And when that happens, the script doesn't work (the image gets hidden if the CSS is set to width: 0 , height: 0 —or if I turn that off then these images are too big for the screen): 发生这种情况时,脚本将不起作用(如果CSS设置为width: 0height: 0或者隐藏了该图像,那么这些图像对于屏幕来说太大了,该图像将隐藏起来):

  window.console.log( iw );
  window.console.log( ih );

  overWidth = iw - ww;
  overHeight = ih - wh;

  if ( overWidth > 0 || overHeight > 0 ) {
    if ( overWidth > overHeight ) {
      // Landscape
      oldW = iw;
      iw = ww - 80;
      ih = (iw * ih) / oldW;
    }
    else {
      // Portrait
      oldH = ih;
      ih = wh - 160;
      iw = (ih * iw) / oldH;
    }
  }

  galleryPrev = galleryPrev || $("<a href='##' class='gallery-prev'>Previous</a>");
  galleryNext = galleryNext || $("<a href='##' class='gallery-next'>Next</a>");

  galleryPrev.attr( "href", (state.prev || state.images[state.images.length - 1]) ).appendTo( imageBox );
  galleryNext.attr( "href", (state.next || state.images[0]) ).appendTo( imageBox );


  // Here I've turned off the CSS adjustments because iw and ih were getting 0s

  if ( iw && iw > 0 && ih && ih > 0 ) {
    image.css({width: iw + "px", height: ih + "px"});
    imageBox.css({width: iw + "px", height: ih + "px"});
  }

}

});

Take a look at: http://www.javascriptkit.com/jsref/image.shtml 看看: http : //www.javascriptkit.com/jsref/image.shtml

You can't calculate the size of an image that hasn't been loaded from the server, but you can load the image via JS using the Image() object and get the calculations you need done before actually inserting that image into the page. 您无法计算尚未从服务器加载的图像的大小,但是您可以使用Image()对象通过JS加载图像,并在将图像实际插入页面之前获得所需的计算结果。

Personally, I would make a PHP script using GD that grabs the dimensions of an image residing on the server and just call it via some AJAX method that returns the results to your JavaScript. 就个人而言,我将使用GD制作一个PHP脚本,该脚本捕获服务器上图像的尺寸,然后通过一些AJAX方法调用该脚本,将结果返回给JavaScript。 Page then never loads the image, which could be beneficial in certain situations where you may need to exclude/modify the image because of it's width/height. 然后,Page永远不会加载图像,这在某些情况下可能是有益的,在某些情况下,由于图像的宽度/高度,可能需要排除/修改图像。

Just a thought. 只是一个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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