在刚刚调用的append函数之后,jquery.height()不会返回实际值

jquery .height() is not returning the real value after the append function just called

本文关键字:返回 jquery append 调用 函数 之后 height      更新时间:2023-09-26

我正在尝试使用jquery垂直对齐中间的一些图片。

这是我的代码

$(".scroll a").hover(function (evt) {
  $("#box a").empty().append( 
    $('<img src='+this.href+' class="loadimg">')
  );
  vertical_align();
});

而垂直对齐功能在这里是

function vertical_align(){
  var child = $(".loadimg").height();
  var parent = $("#box").height();
  var margin = (parent - child)/2;
  $("#box a").children("img").css('margin-top', margin); 
}

现在我面临的问题是,当加载页面时,imageHeight为零,图片的边距变为父高度的一半,这意味着imageheight返回零。但这只是第一次在每张图片上悬停。

发生这种情况可能是因为您读取高度太早,而在第一次请求时图像还没有完全加载。您应该等待图像的加载(或完成,从同一图像的第二个请求开始)事件,就像一样

$(".scroll a").hover(function (evt) {
     var node = $("#box a");
     node.empty(); 
     $('<img src='+this.href+' class="loadimg">')
       .appendTo(node)
       .one('load complete', function() {
           vertical_align();
       });
});