我正在尝试使用 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();
});
});
关于javascript - jquery .height() 在刚刚调用的追加函数之后没有返回真实值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12402702/