2

在以这种方式使用 attr 更改 src 后,我试图在 div 中垂直居中新图像:

$("#image").attr("src",newsrc);
var height = $("#image").height();
var newmargin = (divsize - height)/2;
$("#image").css=("margin-top",newmargin);

它总是使用前一个图像的高度。这是时间问题吗?我是否需要将新高度绑定到某个东西以防止它过早地抓住(以前的图像)高度?

所有图像都在页面加载时预加载...

4

1 回答 1

1

我是否需要将新高度绑定到某个东西以防止它过早地抓住(以前的图像)高度?

有点。load事件应该工作。

$("#image").attr("src",newsrc);
$('#image').load(
    function() {
        var height = $("#image").height();
        // ...
    }
);

http://api.jquery.com/load-event/

于 2010-07-31T06:34:59.890 回答