2011-10-05 165 views
0

我有一个溢出设置为滚动的div,它实质上是逐行地将数据逐行地从一个文件中流出。我想在流溢出时自动滚动到div的底部,但不使用“单击此处滚动到底部”按钮。自动滚动到div的底部

我已经知道scrollTop = scrollHeight solution,但这需要客户端的某种事件触发器。我不希望这个元素是互动的;它应该自动滚动。

有什么办法可以达到这个目的吗?

回答

1

无法将元素自动滚动到底部。使用element.scrollTop = element.scrollHeight

如果你不知道什么时候该元素是要调整,你可以添加一个轮询:

(function(){ 
    var element = document.getElementById("myElement"); 
    var lastHeight = element.scrollHeight; 
    function detectChange(){ 
     var currentHeight = element.scrollHeight; 
     if(lastHeight != currentHeight){ 
      element.scrollTop = currentHeight; 
      lastHeight = currentHeight; 
     } 
    } 
    detectChange(); 
    setInterval(detectChange, 200); //Checks each 200ms = 5 times a second 
})(); 
1

我的一些旧代码与running example,将留在底部时添加的新内容,如果用户滚动它不会更多它的底部。

var chatscroll = new Object(); 
chatscroll.Pane = 
    function(scrollContainerId) 
    { 
     this.bottomThreshold = 25; 
     this.scrollContainerId = scrollContainerId; 
    } 

chatscroll.Pane.prototype.activeScroll = 
    function() 
    { 
     var scrollDiv = document.getElementById(this.scrollContainerId); 
     var currentHeight = 0; 

     if (scrollDiv.scrollHeight > 0) 
      currentHeight = scrollDiv.scrollHeight; 
     else 
      if (objDiv.offsetHeight > 0) 
       currentHeight = scrollDiv.offsetHeight; 

     if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold) 
      scrollDiv.scrollTop = currentHeight; 

     scrollDiv = null; 
    } 
0

很多scrollHeight属性的实现,我没有工作,的offsetHeight似乎这样的伎俩。

很确定scrollHeight试图将它移动到静态元素的高度的底部,而不是可滚动区域的高度。

var pane = document.getElementById('pane'); 
pane.scrollTop = pane.offsetHeight;