简体   繁体   English

所有图像调整大小后如何触发调整大小事件

[英]How to Fire Resize event after all images resize

I have a function that is being called on window resize 我有一个在窗口调整大小时调用的函数

$(window).resize(setVideoElements);

That function sets the height for a class of videoThumbnail containers 该函数设置一类videoThumbnail容器的高度

var setVideoElements = function () { setElementsHeight('.videothumbnail'); };

function setElementsHeight(selector) {

    console.log('setting Max element height');

    // Get an array of all element heights
    var elementHeights = $(selector).map(function () {
        return $(this).height();
    }).get();

    // Math.max takes a variable number of arguments
    // `apply` is equivalent to passing each height as an argument
    var maxHeight = Math.max.apply(null, elementHeights);

    // Set each height to the max height
    $(selector).height(maxHeight);
}

The function works fine except for the fact that its firing too quickly 该功能工作正常,除了它的射击太快

<div class="thumbnail videothumbnail">
  <a href="@Url.Action("Video", new { ID = Video.ID })">
    <img class="videoThumbnailImg" src="@Video.ThumbnailUrl" alt="">
  </a>
  <div class="caption">
     <h3>@Video.Name</h3>
     @foreach (var tag in Video.TagsToVideos)
     {
        <span><a href="#">@tag.Tag.Name</a></span>
     }
  <p>@Video.Description</p>
</div>

The issues is that the function is firing before the images are resize. 问题是函数在图像调整大小之前触发。 I need to fire the resize function after all of the images have already been resized. 我需要在所有图像都已调整大小后触发调整大小功能。

Do anyone know how to fire this function once after all of the images have Resized? 在所有图像都已调整大小后,有没有人知道如何触发此功能?

The <img> HTML Element has an onload callback. <img> HTML元素有一个onload回调。 It fires when the image data has finished downloading from its source. 当图像数据从其源完成下载时,它将触发。 Utilise this to make note of when an image is loaded. 利用它来记录加载图像的时间。 Count the load events and call setElementHeight once all your images are loaded. 计算加载事件并在加载所有图像后调用setElementHeight

An example could look like the below: 示例可能如下所示:

var sources = ['img/a.jpg', 'img/b.jpg', 'img/c.jpg'],
    loaded = 0;

for (var idx in sources) {
  var img = document.createElement('img');
  img.onload = function() {
    loaded++;
    if(loaded === sources.length) {
      setElementHeight();
    }
  }
  img.src = sources[idx];
}

for anyone wondering I needed to clear the fixed height that I set on the resize 对于任何想知道我需要清除我在调整大小上设置的固定高度的人

function clearHeight(selector) {
    $(selector).height('auto');
}

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

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