图像仍在加载时div的动画高度如何?

时间:2014-02-10 20:47:29

标签: javascript jquery css

我的代码通过清空HTML标记并替换内容来显示页面。 加载不同内容时,父div的高度会发生变化,但我无法使高度变化平滑过渡。这可能与仍在加载的图像有关。在这两种状态之间转换的好方法是什么?

// first fade out
$(".page").animate({opacity:0}, 600, function() {
        // then replace html
        $(".page").html("new html here including an <img src='image.jpg'><br>and more text.");
        // now calculate new height and then fade in again
        var endHeight = $(".page").height();
        $(".page").animate({opacity:1, height:endHeight});
});

2 个答案:

答案 0 :(得分:1)

您是否尝试过css过渡?

.YOUR_DIV{
    -webkit-transition:all 0.5s ease-in-out;
    -moz-transition:all 0.5s ease-in-out;
    -o-transition:all 0.5s ease-in-out;
    transition:all 0.5s ease-in-out;
}

答案 1 :(得分:1)

假设您有一个div元素作为内容的容器。如果要加载可能需要一些明显时间加载的内容(例如图像),则可以等待加载该新元素,然后手动重新设置容器的高度。与CSS3过渡一起执行此操作将阻止容器在实际显示内容之前进行动画处理。

来自小提琴:

$(document).ready(function() {

    var container = $('.container');

    /* ... */

    function replaceContent(container) {
        var content = new Image();
            content.onload = function(e) {
                container.empty().append(content);
                container.css({'height': content.height});
            };
            content.src = getRandomImageUrl();
    };

    setInterval(function() { replaceContent(container); }, 5000);

});

关于jsFiddle的工作示例:http://jsfiddle.net/7Vn5a/1/