使用jQuery加载图像后如何触发函数?

时间:2009-06-10 21:56:36

标签: javascript jquery events dom

我正在我正在处理的网站上编写一个简单的图像替换脚本,并且遇到了一些麻烦。

我目前的代码包括:

$(function() {

  // When a thumbnail is clicked
  $(".zoom_thumbs a").click(function() {

    // Get large image attributes
    var largeImg = $(this).attr("href");
    var largeTitle = $(this).children("img").attr("title");
    var zoomImage = $(".zoom_cnt .zoom img");

    //Change the attributes of the large image
    $(zoomImage).attr({ src: largeImg, alt: largeTitle, title: largeTitle });

    // Once the attributes have been changed,
    // reposition the div containing the image to center it
    var wideWidth = $("#wide").width();
    var imageWidth = $(".zoom_cnt").width();
    var marginLeft = (wideWidth - imageWidth) / 2;
    var wideHeight = $("#content").height();
    var imageHeight = $(".zoom_cnt").height();
    var marginTop = (wideHeight - imageHeight) / 2;
    $(".zoom_cnt").css("left", marginLeft);
    $(".zoom_cnt").css("top", marginTop);

    return false;
  });
});

我已经发表了一些评论,向您展示我在每一步中所做的工作以及我想要实现的目标。我的问题是我希望在更改图像属性后重新定位包含图像的div。目前它没有,除非我再次点击缩略图(我认为这是因为图像已经加载并且在缓存中?)。我想做的是什么?

非常感谢任何帮助:)

P.S我知道一旦完成这些图像就会跳起来,但是一旦修复了,我就会做隐藏/显示效果。

1 个答案:

答案 0 :(得分:3)

您希望使用映像的load事件来触发执行依赖于已加载属性的代码:

//Change the attributes of the large image
$(zoomImage)
  .load(function()
  {
    // Once the attributes have been changed,
    // reposition the div containing the image to center it
    var wideWidth = $("#wide").width();
    var imageWidth = $(".zoom_cnt").width();
    var marginLeft = (wideWidth - imageWidth) / 2;
    var wideHeight = $("#content").height();
    var imageHeight = $(".zoom_cnt").height();
    var marginTop = (wideHeight - imageHeight) / 2;
    $(".zoom_cnt").css("left", marginLeft);
    $(".zoom_cnt").css("top", marginTop);
  })
  .attr({ src: largeImg, alt: largeTitle, title: largeTitle });

使用纯CSS也可能有办法做到这一点,但由于你没有指定你正在使用的标记的结构,我无法真正推测它。

相关问题