将jquery调用附加到图像加载

时间:2014-02-21 02:59:49

标签: javascript jquery

我正在尝试合并一个脚本(我认为是“dystroy”),它将图像垂直居中在div中,并隐藏溢出。它工作得很好,但我的许多图像都是在鼠标悬停时动态加载的。

我需要找到一种在图像加载时调用脚本的方法。现在已经两天了,由于JS / JQuery不是我的母语,我在这里找到了自己。

任何人都可以建议我如何在图片加载时触发以下内容? 非常感谢!

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
  $('.container').each(function () {
    var $img = $(this).find('img');
    $(this).scrollTop(($img.height() - $(this).height()) / 2);
    $(this).scrollLeft(($img.width() - $(this).width()) / 2);
  });
});
//]]></script>  

2 个答案:

答案 0 :(得分:0)

也许你可以结合加载api(https://api.jquery.com/load/):

$("#book").load(function() {
  // Handler for .load() called.
});

使用事件委托来使其在任何指定div中加载的任何新图像都获得应用了onload函数(https://learn.jquery.com/events/event-delegation/):

// attach a delegated event
$("#list").on("click", "a", function(event) {
  event.preventDefault();
  console.log($(this).text());
});

答案 1 :(得分:0)

$(document).ready(...在执行函数之前,将等到页面上的所有内容都被加载(包括图像)。

<script type='text/javascript'>//<![CDATA[ 
$(document).ready(function(){
  $('.container').each(function () {
    var $img = $(this).find('img');
    $(this).scrollTop(($img.height() - $(this).height()) / 2);
    $(this).scrollLeft(($img.width() - $(this).width()) / 2);
    });
});
//]]></script>