Skip to main content
 首页 » 编程设计

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

2024年05月10日37lonelyxmas

我有一个在调整窗口大小时调用的函数

$(window).resize(setVideoElements); 

该函数设置一类视频缩略图容器的高度

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); 
} 

除了触发速度太快之外,该功能工作正常

<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> 

问题是该函数在调整图像大小之前触发。在调整所有图像的大小后,我需要触发调整大小功能。

有谁知道如何在所有图像调整大小后立即触发此功能?

请您参考如下方法:

<img> HTML 元素有一个 onload打回来。当图像数据从其源下载完成时,它会触发。使用它来记录图像何时加载。计算加载事件并调用 setElementHeight加载所有图像后。

示例如下所示:

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]; 
}