[英]Scroll to bottom of hidden div?
我有一个简单的聊天JS应用程序,一个div.chat-holder
在整个窗口的窗格中保存所有聊天消息。 我设置' .chat-holder
高度,使其保持固定大小,并允许滚动所有消息。
<style>
.chat-holder {
height: 30px;
overflow-y: scroll;
}
</style>
<div class="pane">
<div class="chat-holder">
<div class="chat-item">
first msg
</div>
<div class="chat-item">
second msg
</div>
....
<div class="chat-item">
last msg
</div>
</div>
</div>
在页面加载时,我通过设置持有者的scrollTop滚动到底部:
var $holder = $('.chat-holder');
$holder.scrollTop($holder[0].scrollHeight);
这很好用。
当我将div.pane
设置为display:none
时,会出现问题。 理想情况下,我希望有一个单独的事件来“显示/隐藏”聊天窗格,并从隐藏的窗格开始。
隐藏父窗格时, .chat-holder
scrollHeight为0,因此在加载时 ,隐藏窗格将不会滚动到底部。 这意味着当显示窗格时,聊天不会滚动到最近的聊天。 您可以在以下代码段中看到这一点:最初未显示.pane
,未设置滚动。 如果将.pane
设置为开始显示,则滚动工作正常。
在父母被隐藏的时候,有没有“滚动到底部”? (是的,我知道我可以通过检测聊天持有者何时暴露然后滚动到底部来做到这一点,但我希望在加载时这样做。)
$(function() { var $holder = $('.chat-holder'); $holder.scrollTop($holder[0].scrollHeight); $('button').click(function() { $('.pane').toggleClass('active'); }); });
.chat-holder { height: 30px; overflow-y: scroll; border: thin solid black; } .chat-item { font-size: 20px; } .pane { display: none; } .pane.active { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="pane"> <div class="chat-holder"> <div class="chat-item">first msg</div> <div class="chat-item">second msg</div> <div class="chat-item">last msg</div> </div> </div> <button>Toggle pane</button>
您可以获得创意并使用opacity
或visibility
规则而不是display: none
:
$(function() { var $holder = $('.chat-holder'); $holder.scrollTop($holder[0].scrollHeight); $('button').click(function() { $('.pane').toggleClass('active'); }); });
.chat-holder { height: 30px; overflow-y: scroll; border: thin solid black; } .chat-item { font-size: 20px; } .pane { opacity: 0; position: absolute; z-index: 1; } .pane.active { opacity: 1; position: relative; } button { z-index: 2; position: relative; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="pane"> <div class="chat-holder"> <div class="chat-item">first msg</div> <div class="chat-item">second msg</div> <div class="chat-item">last msg</div> </div> </div> <button>Toggle pane</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.