繁体   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