【问题标题】:Using max-width = 100% and max-height = 100% on an image, calculate the display width/height在图像上使用 max-width = 100% 和 max-height = 100%,计算显示宽度/高度
【发布时间】:2010-02-13 03:09:44
【问题描述】:

我正在为各种尺寸的图像创建幻灯片,以在画布区域内垂直和水平居中显示。

在我的 CSS 中,我将图像的宽度和高度设置为 100%,以便每个图像按比例填充画布。我希望画布自动调整大小以适应查看者的屏幕尺寸,因为图像的原始尺寸非常大(高达 800 像素)。

我正在使用 jQuery 1.4,并使用图像的高度来计算顶部值,以便将其绝对定位到画布的中间。

我尝试使用 jQuery 来获取 .height()、innerHeight() 和 outerHeight(),但它总是获取图像的完整尺寸。

我从 jQuery 对象中提取 DOM 元素并尝试使用 .width、.offsetWidth 和 .clientWidth,但这似乎总是返回图像的完整大小。

Firebug 显示正确的尺寸,所以我知道有一些方法可以计算图像的实际显示高度,但我无法弄清楚它是什么。如果设置了 max-height = 100%,如何获得图片的实际显示高度?

我不想在 js 中计算和设置每个图像的高度,但如果必须,我会的。看来我应该能够设置画布大小并自动调整图像。

【问题讨论】:

标签: javascript jquery image getimagesize


【解决方案1】:

我建议将图像转回自动,然后获取图像值,然后将它们设置回 100%。

$('img').each(function(){
   var self = $(this);
   self.hide() // Hide them, fading, you choose
      .css({'width':'auto', 'height':'auto'}) // set them to auto.
      .data('width', self.width())  // Now you can get the real size
      .data('height', self.height()) // And store it as jQuery data in the image.
      .css({'width':'100%', 'height':'100%'}) // Back to 100%
      .show();  // Show them.
});

或者,其他方式

$('img').hide().css({'width':'auto', 'height':'auto'})
   .each(function(){
      var self = $(this);
      self.data('width', self.width())
          .data('height', self.height());
   })
   .css({'width':'100%', 'height':'100%'}).show();

或者不需要隐藏它们,因为可能更改太快了,但您可能需要对逻辑进行一些调整,以便用户在第一次加载时不会看到眨眼。

不管怎样,选择你的毒药。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2012-02-26
    相关资源
    最近更新 更多