【问题标题】:Image height returns 0 on appended element附加元素上的图像高度返回 0
【发布时间】:2018-07-03 13:45:44
【问题描述】:

我正在附加 div,我需要获取图像高度和宽度。我需要根据图像的高度/宽度将css添加到MB-Container类中

示例:纵向 -> 容器宽度 100%,横向 -> '自对齐':'flex-end'

$('.MB-Container').append('' +
  '<div class="Cover-Item">' +
    '<img src="' + cover + '" style="width:100%; height:100%;"/>' +
    '</div>' +
  '</div>');

但是,当尝试获取图像的高度和宽度时,我的高度为零:

var itemWidth = $('#item1 .Cover-Item img').width();
var itemHeight = $('#item1 .Cover-item img').height();

如何在 append 中添加 onload 函数来检查图像的宽度/高度?

我试过了:

$(document).on("load",".Cover-Item img", function() {

}).each(function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
   console.log($(this).load());
     $(this).load();
});

但这只会触发一次。

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

在您的示例中,实际的 onload 函数是空白的。这可能有效:

$(document).on("load",".Cover-Item img", function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
   console.log($(this).height());
});

【讨论】:

  • 哈哈.. 哎呀。我确实添加了它,但它只触发一次。虽然我有更多图片。
  • 整个命令何时运行? .on() 仅适用于首次运行时存在的元素。请参阅 peeebeee 的链接。
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多