2011-11-07 36 views
1

我有一個不斷流式傳輸數據的div,並具有允許它自動滾動到底部的功能,將最新信息始終放在用戶的視線中。jQuery - 當onfocus = true時停止自動滾動

但是,我當前實現的問題是,此元素不關心用戶是否希望向上滾動並查看之前打印的行。只要新數據是POSTed,div就會將滾動條拉回到底部。考慮到更新經常發生(〜500毫秒),這對於想要在自己的閒暇時間查看整個日誌的用戶來說是相當令人不快的。

理想的情況下,這裏就是我想要做這個div

  • 當DIV本身,或滾動條(overflow:auto)內的用戶點擊,自動滾動立即被禁用。
  • 只要用戶在外面點擊,自動滾動就會重新啓用。
  • 當第一次加載頁面,股利,默認情況下,設置爲不集中(如果用戶不點擊任何地方即自動滾動發生)

代碼:

<script type="text/javascript"> 
    $(function() { 
     $("#testMonitor").everyTime(500, function() { 
      $("#testMonitor").attr({ scrollTop: $("#testMonitor").attr("scrollHeight") - $('#testMonitor').height() }); 
     }); 
    });   
</script> 

<script type="text/javascript"> 
    $("div#testMonitor").attr("tabindex", -1).focusin(function() { 
     $("#testMonitor").attr({ scrollTop: $("testMonitor").height() }); 
    }); 
</script> 

第一個塊是我的自動滾動,它按預期工作。第二部分應該在onFocus上將scrollTop設置爲「正常」高度。

如何修改我的focusin函數以按照需要運行?

回答

3

比你想象的要容易得多。

1)創建一個標誌

var autoScrollEnabled = true; 

2)修改自動滾動,則僅當autoScrollEnabled是真的

$(function() { 
    $("#testMonitor").everyTime(500, function() { 
     if (autoScrollEnabled == true) { 
      $("#testMonitor").attr({ scrollTop: $("#testMonitor").attr("scrollHeight") - $('#testMonitor').height() }); 
     } 
    }); 
}); 

3)添加代碼來切換自動滾動的地方適當的

toggleAutoScroll(); 

function toggleAutoScroll() { 
    autoScrollEnabled = !autoScrollEnabled; //! reverses the value, true becomes false, false becomes true 
    if (autoScrollEnabled == true) { //scroll down immediately if a.s. is reenabled 
     $("#testMonitor").attr({ scrollTop: $("#testMonitor").attr("scrollHeight") - $('#testMonitor').height() }); 
    } 
} 
+0

謝謝,你的解決方案工作。抱歉需要花一些時間弄清楚,邏輯需要點擊我的腦海,然後我必須弄清楚如何使div對焦/模糊等。 – Kevin