jQuery scrollTop函数在ajax调用后无法正常工作

时间:2014-04-23 14:23:14

标签: jquery css ajax jquery-ui

这是我的ajax调用...工作正常但Jquery的scrollTo插件并没有将内容定位在我想要的位置。以下

 //this will show the contents of the email body when the list item is clicked.
    jQuery("#list-item-"+username+"").click(function(){

        jQuery(".reply-to-container").hide();
        jQuery("#reply-to-"+username+"").toggle("slide", {direction: 'up'});
        jQuery("#reply-input-"+username+"").val('');
        jQuery(".display-reply-content").html("");
        jQuery("#send-btn-ajax-"+username+"").hide();
        jQuery("#reply-input-"+username+"").hide("slide", {direction: 'up'});


        var myUsername = getUrlVars()['username'];
        var messageID = <?php echo $this->message_id; ?>;
        var dataString = 'messageID='+ messageID + '&friend=' + username + '&myUsername=' + myUsername;

        $.ajax({
            type: "POST",
            url: "/friends/mark-read/", 
            data: dataString,
            cache: false,
            success: function(html)
            {    
                jQuery("#mail-icon-"+username+"").replaceWith("<div id='mail-icon-"+username+"' class='ui-icon ui-icon-mail-open mail-closed'>");
                jQuery("#display-reply-"+username+"").css({"display" : "none"}).html(html).fadeIn(2500);
                console.log(jQuery("#display-reply-"+username+"")[0].scrollHeight);
                jQuery("#display-reply-"+username+"").scrollTop(jQuery("#display-reply-"+username+"").scrollHeight);

            },
            error: function(jqXHR, textStatus, errorThrown) 
            {
                console.log(textStatus, errorThrown);
            }
        }) 
    })

这是我的Div的CSS

.display-reply-content{
    max-height: 200px;
    overflow: auto; 
    }

2 个答案:

答案 0 :(得分:0)

我认为您需要更改内容滚动到容器高度的位置:

var $content = jQuery(".display-reply-content");
$content.scrollTop($content[0].scrollHeight);

尝试在AJAX调用中添加错误函数以处理任何错误:

$.ajax({
        type: "POST",
        url: "/friends/mark-read/", 
        data: dataString,
        cache: false,
        success: function(html)
        {    
            //...
        },
error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}
...

答案 1 :(得分:0)

这似乎解决了这个问题:

jQuery("#display-reply-"+username+"").css({"display" : "none"}).html(html).fadeIn(1500, function() {
                    jQuery("#display-reply-"+username+"").scrollTop(jQuery("#display-reply-"+username+"")[0].scrollHeight);
                });