2013-05-22 263 views
2

我使用mCustomScrollbar作爲頁面上的元素,它有時會重新加載。這是一個消息視圖,當用戶點擊另一個對話時,會話的消息被加載。然而,當我想在加載這個後滾動到底部時,因爲最新的消息在底部,它不滾動到底部,而是底部幾個像素(「幾個」可以在10和200px之間隨機)。jQuery自定義內容滾動器不滾動到底部

下面是一個簡單的例子:

// code to load another conversation 
$(".conversations .conversation").click(function (e) { 
    var $this = $(this); 
    $.ajax({ 
     url: W.sprintf('/messages/%s/fetch', $this.attr("data-cid")), 
     dataType: 'html' 
    }).done(function(data) { 
     $('.main_pane.messages').html(data); 
     // a function call to set the hight of .main_list.messages goes here 
     $(".main_list.messages").mCustomScrollbar(W.scroll_prefs); 
     $(".main_list.messages").mCustomScrollbar("scrollTo", "bottom"); 
     // also tried adding an element at bottom and scrolling to this 
     // and scrollTo Number.MAX_VALUE 
     // also tried putting the two mCustomScrollbar lines both into 
     // setTimeout() 
    }); 
}); 
<!-- this is what gets loaded --> 
#conversation 
    .head 
    -# some foo 
    .conv_body 
    .main_list.messages.custom-scroll.hide-scrollbar.start-bottom 
     -# basically a bunch of these below 
     .listelem.msg 
     .left 
      = image_tag(user.avatar.image(:icon), size: avatar_size(:icon)) 
     .right 
      %span.datetime= fmt_time(msg[:datetime], :time) 
     .middle 
      .name= link_to(user.login, user) 
      .text= msg[:text] 
    #new_message_container.main_input.open.threeline 
     = form_for(@message) do |f| 
     -# ... 

CSS:短短邊距和補和顏色之類的東西,沒有什麼花哨

回答

4

看來你初始化插件每次有新內容通過ajax加載。你應該初始化插件一旦(click事件外):

$(".main_list.messages").mCustomScrollbar(W.scroll_prefs); 

當Ajax調用完成後,新的內容是滿載,叫mCustomScrollbar更新方法(更新根據新內容的滾動條),然後滾動到下:

$(".main_list.messages").mCustomScrollbar("update"); 
$(".main_list.messages").mCustomScrollbar("scrollTo", "bottom"); 
+0

我必須這樣做,因爲我銷燬並重新創建了滾動條所在的元素。如果我只是用你所建議的更新替換初始化,我會得到一個錯誤,因爲滾動條知道/正在打開的元素不再存在:Uncaught TypeError:無法讀取未定義jquery.mCustomScrollbar.concat的屬性'offsetTop'。 min.js?body = 1:5 請糾正我,如果我錯了 – linopolus

+1

我不知道你的HTML代碼是如何(.main_pane.messages和.main_list.messages堆棧),但也許這可能會有所幫助.. 。您的原始內容(在.main_list.messages中)駐留在.mCSB_container div中,所以也許可以在.mCSB_container(而不是直接.main_pane.messages)中附加ajax數據。我不知道這是否可行,因爲我不知道你的html代碼。 此外,您可以嘗試用'always'或'complete'替換'done',因爲在調用scroll-to-bottom(加載圖像?)時,內容似乎並未完全加載。你也可以在scrollTo中加入1秒的時間間隔。 – malihu

4

我有同樣的問題,首先調用更新,然後加入1000超時之前我所說的scrollTo底解決它

$('#commentArea .mCSB_container ').append('<span class="oneComment">'+outputText+'</span><span class="commentBreaker"></span>'); 
$("#commentArea").mCustomScrollbar("update"); 
    setTimeout(function(){ 
     $("#commentArea").mCustomScrollbar("scrollTo","bottom"); 
    },1000); 
+0

這爲我工作。 – user1063287

+0

也爲我工作 –

0

我用:

var d = $('#selector'); 
d.mCustomScrollbar({ 
    setTop: d.height() + "px" 
}); 

,開始以DIV的底部。

0

嘗試添加填充到您調用自定義滾動條的容器底部。

.main_list.messages 
{ 
    padding-bottom: 10px; 
}