想象一个带有填满页面的消息线程的表格 - 用户将自动向下滚动到线程的末尾和页面的底部。底部有一个文本区域,通过 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.');
});
这样做的妙处在于效果确实有效。但是,通过附加表格,用户会被“推”到页面底部上方大约 100 像素 - 他不会停留在底部。
如何解决这个问题,以便在发送消息并附加表格后,用户仍然停留在页面底部?
最佳答案
要移动到页面底部,您可以使用 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());
}
}
关于jQuery - 留在页面底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12299987/