如果您已经注意到,似乎使用prepend()时,其他元素会堆积在顶部,但容器div会向下延伸。

与FB的上一个加载消息相比,您会注意到元素被相互加载,但是您的视图没有改变。就像append()一样,只是容器div“似乎”向上延伸。

我尝试这样做以模拟div向上延伸,但失败了

var scrolldif = $('#response')[0].scrollHeight-$('#response').scrollTop();
$('#response').scrollTop(scrolldif);


这是尝试的示例html。只需在浏览器中复制/粘贴/运行即可。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
    .chatbox div{
        height: 100%;
    }
    #response{
        height: 300px;
        overflow-y: scroll;
        overflow-wrap: break-word;
    }

</style>
<script type="text/javascript">
    function appendMessage()
    {
        var data = 'test';
        var message = document.createElement('p');
        message.innerHTML = data;
        $('#response').append(message);
    }

    function prependMessage()
    {
            var data = 'test'+Math.floor((Math.random() * 10) + 1);
            var message = document.createElement('p');
            message.innerHTML = data;
            console.log(message.innerHTML);
            $('#response').prepend(message);
    }

</script>
<body>
<div class="container">
    <div class="chatbox">
        <div class="col-sm-8 rightP">
            <div class="row contents">
                <a onclick="return appendMessage()" class="load btn btn-default">Append</a>
                <a onclick="return prependMessage()" class="load2 btn btn-default">Prepend</a>
                <div class="row msg">
                    <div id="response" class="msg form-group">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>


谢谢!

最佳答案

我终于找到了答案,但是如果有更好的解决方案,那就分享一下!看来我以前的试用确实有效,但是scrolldif的位置是指向容器div的顶部的,所以我反过来从底部开始引用它,如下所示:

$('#response').scrollTop($('#response')[0].scrollHeight-scrolldif);


在我上面的代码中,只需执行以下操作:

function prependMessage()
{
    //this scrollHeight is the total height of div including hidden parts of the
    //div caused by overflow BEFORE elements were prepended to it.
    var scrolldif = $('#response')[0].scrollHeight-$('#response').scrollTop();

    for(var $i = 0;$i<10;$i++)
    {
        //prepend elements....
    }

    //this scrollHeight is the total height of div including hidden parts of the
    //div caused by overflow AFTER elements were prepended to it.
    $('#response').scrollTop($('#response')[0].scrollHeight-scrolldif);
}


尽管'div'不会扩展到顶部,但似乎只是通过调整容器div的scrollTop值来扩展。如果有更好的解决方案,请分享!

09-25 17:02
查看更多