簡體   English   中英

滾動到動態Div的底部

[英]Scroll to the Bottom of Dynamic Div

我有一個id為“ page-content”的div ,它沒有高度寬度 ,它只有一個空白的div

我正在用該內容動態填充該div ,所以div高度不斷增長,正在聊天,我想檢測自己是在div的底部還是在div總高度的最后10% ,如果為true,則滾動到底部

var box = $('#page-content');
if (box.scrollTop() > (box.height*0.90))
    box.scrollTop(25000); // This is the top bottom

我想做的是,檢查您是否位於"#page-content" div的最后一個底部高度的10%或以下(不是當我在Div的開頭閱讀“舊消息”時),我有一個附加新消息的功能,但我需要手動向下滾動才能看到新消息...所以我想自動滾動到“ 底部”,以便可以看到新消息:)

更新:

function getChat() {
  $.ajax({
    type: "GET",
    url: "refresh.php?lastTimeID=" + lastTimeID
  }).done( function( data )
  {
    var jsonData = JSON.parse(data);
    var jsonLength = jsonData.results.length;
    var html = "";
    for (var i = 0; i < jsonLength; i++) {
      var result = jsonData.results[i];
      html += '<span class="color-'+result.color+'"><b>'+result.usrname+'</b></span> <i class="fa fa-angle-right"></i> '+result.chattext+'<br>';

      lastTimeID = result.id;     
    }
    $('#page-content').append(html);

    if(html!="")
    {   
     // Here i need to check if the scroll position is in the bottom or in the last 10%
     //then this to scroll to the top bottom (25000 is height limit)
     $('.page-content').scrollTop(25000);
    }

  }); }

將頁面滾動到DIV底部有一個技巧,我試圖在這個小提琴中實現它。

請參閱$(window).height()+$(window).scrollTop()將始終等於$(window).height()+$(window).scrollTop()的總高度(包括填充,邊距),在我們的示例中,它等於$('#page-content').height()+margin/padding

CSS:

div#page-content {
  height:600px;
  border:solid 1px red;
}

在我們的情況下:

$(window).height()+$(window).scrollTop()=$('#page-content').height()+(margin/padding)=600px

因此,每當scroll它時,我們都可以將scroll()事件附加到div並輕松檢查我們是否位於“#page-content”的頂部底部高度的最后10%或更少的位置

$(window).on('scroll',function(){

   if($(window).height()+$(window).scrollTop()>=($('#page-content').height()*(.9))){
     $(window).scrollTop($('#page-content').height()-$(window).height())
   }
})

祝好運。

由於我沒有這樣做,所以我不想為此功勞。

有一個jQuery插件,可以使具有滾動條的所有內容滾動到特定位置或元素。 由於要滾動到動態div,因此可以在創建div之后調用它,它將滾動到該位置。

您可以在這里找到插件

您可以在此處找到該插件的演示

希望這就是您想要的。

-W

訣竅是在您的郵件容器內(在您的情況下為#page-content DIV),您可以在其中設置一些id的不可見占位符div

此演示JSFiddle中 ,單擊錨點.addItem ,將新項目添加到容器后, 占位符div移動到容器的末尾 這樣可以確保同時單擊.addItem將容器DIV的底部顯示在視圖中( 因為它在href屬性中引用了占位符的id )。

function scrollToBottom(container) {
    // get all the child elements of the container
    var children = container.children('.item');

    // move the placeholder to the end of the container
    $('#contentBottom').insertAfter(children.eq(children.length - 1));
}

更新

為了確定您當前的滾動位置,您應該監聽 container scroll事件。 同時,當新消息到達時,您應考慮container更新高度值。

查看此更新的小提琴 ,我在其中檢查當前滾動位置是否從頂部超過60%,以輕松查看效果。

注意:如果在不滾動時出現新消息,則只需在將其附加到container的同一函數/代碼塊中執行$('.container').scrollTop(25000)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM