我使用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:短短邊距和補和顏色之類的東西,沒有什麼花哨
我必須這樣做,因爲我銷燬並重新創建了滾動條所在的元素。如果我只是用你所建議的更新替換初始化,我會得到一個錯誤,因爲滾動條知道/正在打開的元素不再存在:Uncaught TypeError:無法讀取未定義jquery.mCustomScrollbar.concat的屬性'offsetTop'。 min.js?body = 1:5 請糾正我,如果我錯了 – linopolus
我不知道你的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