jQuery - 留在页面底部

时间:2012-09-06 12:19:11

标签: jquery ajax

想象一个带有填充页面的消息线程的表 - 用户将自动向下滚动到线程的末尾和页面的底部。底部有一个textarea,通过ajax和php,在按钮点击时发送消息并附加表格。

以下是执行此操作的代码:

//Call script to send message
$.ajax({
    type: 'POST',
    url: 'action/sendmessage.php',
    data: 'partner='+partner+'&message='+message,
    success: function(feedback){
        var json=$.parseJSON(feedback);
        if(json.success=='true'){
            $('#messagetext').val('');
            $('table > tbody:last').hide().after(json.message).show(200);
            $('#messagetext').focus();
        }
    }
}).error(function(){
    alert('The message could not be sent - please try again later.');
});

关于这一点的巧妙之处在于效果是有效的。但是,通过附加表格,用户可以“推”到页面底部约100px - 他不会底部。

如何解决这个问题,以便在发送邮件并附加表格后,用户仍然会停留在页面底部?

2 个答案:

答案 0 :(得分:3)

要移至页面底部,您可以使用scrollTop()方法。就个人而言,我会为滚动设置动画,因为单独移动的页面可能会让您的某些用户感到困惑。试试这个:

success: function(feedback){
    var json = $.parseJSON(feedback);
    if (json.success=='true'){
        $('#messagetext').val('');
        $('table > tbody:last').hide().after(json.message).show(200);
        $('#messagetext').focus();

        // animate scrolling to bottom of the page
        $("html, body").animate({ scrollTop: $(document).height() }, 500); 

        // jump directly to the bottom of the page
        //$("html, body").scrollTop($(document).height()); 
    }
}

答案 1 :(得分:0)

添加此功能somehwere

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(doc.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(doc.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(doc.body.clientHeight, D.documentElement.clientHeight)
    );
}

然后将其添加到处理程序:

window.scrollTo(0, getDocHeight());

它会将页面滚动到底部。

这应该可以解决你的问题。

相关问题