我需要一个区域,当新文本来自ajax请求时会自动滚动到底部
CSS
div.scroll {
height: 400px;
width: 95%;
overflow: auto;
/* border: 1px solid #666; */
background-color: #ccc;
padding: 8px;
}
HTML
<html>
<head>
<script type="text/javascript">
//Handle ajax data
$(document).ready(function()
{
setInterval(doAjaxStuff, 2000);
});
function doAjaxStuff()
{
$.ajax
({
url: "http:somewhere/getLog/",
dataType: 'json',
success: function(json)
{
if(json.status == "on")
{
$('#log').html(json.log);
}
}
});
</script>
</head>
<body>
<div class="scroll" id =log >pleas wait for log</div>
</body>
</html>
答案 0 :(得分:2)
您可以使用scrollTop()
功能:
//will only auto-scroll if scroll position is already at bottom
var doAutoscroll = ($("#log").scrollTop()==$("#log")[0].scrollHeight);
$('#log').html(json.log)
if (doAutoscroll) $("#log").scrollTop($("#log")[0].scrollHeight);