2011-08-18 21 views
0

時如何獲得自動滾動到一個div工作的底部我需要自動滾動到下一個區域時,新文本從一個Ajax請求採用div類

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> 

回答

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);