【问题标题】:How to Fire Resize event after all images resize如何在所有图像调整大小后触发 Resize 事件
【发布时间】:2016-03-25 19:35:17
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript c# model-view-controller razor


    【解决方案1】:

    &lt;img&gt; 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];
    }
    

    【讨论】:

    • 这是有道理的,你知道如何在没有所有事件处理程序的情况下做到这一点吗?
    • 没有事件处理程序是什么意思?关键是要利用 onload 事件,所以你需要事件处理程序。
    • 我的意思是不为每个图像添加一个,它们是从无限滚动算法动态加载的,所以我必须将负载绑定到正文。这肯定会起作用,尽管我只是希望有一种方法可以绑定到容器或其他东西,但我不知道我想要的是否可能
    • 我想我弄错了,图像已经加载了我只需要在调整img大小后触发函数
    【解决方案2】:

    对于任何想知道我需要清除我在调整大小时设置的固定高度的人

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

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多