我有一个基于 Bootstrap 的模式,允许用户添加和查看帖子:
<div class="modal fade hide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="prodCommentModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-title">Comments</div>
</div>
<div class="modal-body" data-no-turbolink>
<span id="modal-body-span">
<%= render partial: 'posts/getposts' %>
</span>
</div>
<div class="modal-footer">
<%= form_for(@micropost) do |f| %>
<div class="field" id="post-box">
<%= f.text_area :content, placeholder: "Write a post..." %>
</div>
<div class="post-submit">
<%= f.submit "Post", id: "post_button", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
</div>
为了在添加新帖子时保持模式打开,我有以下 JavaScript:
$(document).ready(function() {
$('#post_button').click(function (e) {
e.preventDefault();
$.post('/posts',
$('#new_post').serialize(),
function (data, status, xhr) {
$('.modal-body').load(document.URL+' #modal-body-span');
$('.modal-body').scrollTop($('.modal-body').prop("scrollHeight"));
$('#post_content').val('');
});
});
});
该模式以聊天方式完成,最新的帖子添加到底部。我有单独的 javascript,当模态首次打开时,它会自动将模态主体区域滚动到底部。但我无法开始工作的是提交新帖子后滚动到底部(当模式仍然打开时)。我观察到了一些事情:
- 如果我在加载前后打印 $('.modal-body').prop("scrollHeight") ,则该值不会改变。
- 如果我向上滚动帖子,然后使用较大的值,例如 $('.modal-body').scrollTop(10000),它会在提交后向下滚动,但滚动到上一篇帖子的底部。
看来scrollheight会稍后更新,直到更新为止,scrollTop最多只会滚动到旧值。有什么想法吗?
最佳答案
经过多次尝试,终于找到了可行的方法(ajaxComplete 事件)。我还需要解决自上次重新加载页面/模式以来可能已添加新帖子的问题,并且我想要模式中最新和最好的内容。
$(document).ready(function() {
$('#post_button').click(function (e) {
e.preventDefault();
$.post('/posts',
$('#new_post').serialize(),
function (data, status, xhr) {
$('.modal-body').load(document.URL+' #modal-body-span');
$('#post_content').val('');
});
});
$(document).on('show.bs.modal', '.modal', function () {
$('.modal-body').load(document.URL+' #modal-body-span');
});
$(document).ajaxComplete(function() {
$('.modal-body').scrollTop($('.modal-body').prop("scrollHeight"));
});
$('#myModal').on('shown.bs,modal', function () {
$('.modal-body').scrollTop($('.modal-body').prop("scrollHeight"));
});
});
如果有更好或更优雅的解决方案,我仍然很乐意听到它们。
关于javascript - 在 Bootstrap 模式中重新加载 div 后使用scrollTop 时,不会考虑新高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24297754/