JQuery滚动到Bootstrap Modal的顶部

时间:2013-06-18 23:23:32

标签: javascript jquery twitter-bootstrap

我目前正在使用bootstrap模式插件在我正在设计的网站上显示长法律消息,但问题是如果你打开另一个模态,第二个已经滚动到任何位置第一个是。所以我正在寻找一种使用JS / JQuery将div滚动到顶部的方法。这是我目前正在使用的代码:

HTML:

<!--MODAL-->
<div id="modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="modalTitle" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="modalTitle"></h3>
</div>
<div id="modal-content" class="modal-body">
</div>
<div class="modal-footer">
<button id="modalPrint" class="btn btn-info hidden-phone" onClick=''>Print</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>

使用Javascript:

function openModal(heading, url) {
    $.ajax({
    url: url,
    cache: false
    }).done(function( html ) {
    $("#modal-content").html(html);
    $("#modalTitle").html(heading);
    $('#modalPrint').attr('onClick', 'loadPrintDocument(printCookies, {attr : "href", url : '+ url +', showMessage: false, message: "Please wait while we create your document"})');
    $('#modal').modal('show');
    $("#modal-content").scrollTop(0);
    });
}

正如您所看到的,我已经尝试在模式显示后滚动到顶部。有什么想法吗?

7 个答案:

答案 0 :(得分:54)

现在有了bootstrap 3,事件发生了变化,可以像这样实现(加上一个平滑的动画到顶部)

$('#modal').on('shown.bs.modal', function () {
    $('#modal').animate({ scrollTop: 0 }, 'slow');
});

答案 1 :(得分:43)

好的,我已经回答了我自己的问题。对于有此问题的其他人,只需将此功能添加到您的JS!

$('#modal').on('shown', function () {
    $("#modal-content").scrollTop(0);
});

我会留下这个问题,因为没有一个类似的(我能找到)并且它可以帮助某人

答案 2 :(得分:5)

On Bootstrap 4(v4.0.0-alpha.6)以下版本对我来说效果很好:

$('#Modal').show().scrollTop(0);

请注意,从 bootstrap-4.0.0-beta.1 Firefox 56.0.1 开始,这似乎无法正常工作;

我检查了IE11,MS Edge和Chrome,这很好用。

答案 3 :(得分:3)

  1. 向上滚动按钮的类别为: .page-scroll
  2. enter image description here

    1. 类型为 .modal

      的模态

    2. JS使用模态进行滚动(JS可以简化):

      $('body').on('click', '.page-scroll', function(event) {
          var $anchor = $(this);
          $('html, body, .modal').stop().animate({
              scrollTop: $($anchor.attr('href')).offset().top
          }, 1500, 'easeInOutExpo');
          event.preventDefault();
      });
      

答案 4 :(得分:2)

你需要使用的boostrap有变化:在shown.bs.modal上

显示模态窗口时调用函数(我选择了此方法)

<button onclick="showSMSSummary(); return false;" 
data-toggle="tooltip" title="Click To View Summary" 
class="btn btn-primary btn-sm">SMS Summary</button>

function showSMSSummary()
{
   $('#HelpScreenModalContent').modal('show');            
   $('#HelpScreenModal').animate({ scrollTop: 0 }, 'fast');
}

答案 5 :(得分:2)

在Bootstrap 4中,以下对我有用:

$('.modal-body').scrollTop(0);

您需要在模态主体上滚动top,因为父元素(模态,模态对话框,模态内容)是容器,并且不会随用户滚动。

但是,如果您希望动作比较平稳,请尝试以下动画路线:

$('.modal-body').animate({scrollTop: 0},400);

答案 6 :(得分:0)

ScrollTop bootbox modal on fadeIn答案就在这个问题上。

设置启动箱对话框时,最后添加.off("shown.bs.modal");

bootbox.dialog({ ... }).off("shown.bs.modal");

打开对话框时会滚动到顶部。