JQuery滚动到Bootstrap Modal的顶部

Adi*_*eld 47 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>
Run Code Online (Sandbox Code Playgroud)

使用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);
    });
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我已经尝试在模态显示后滚动到顶部.有任何想法吗?

小智 58

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

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


Adi*_*eld 47

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

$('#modal').on('shown', function () {
    $("#modal-content").scrollTop(0);
});
Run Code Online (Sandbox Code Playgroud)

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

  • 这是一个类。`.modal-content` (2认同)

Ber*_*rdV 8

在Bootstrap 4(v4.0.0-alpha.6)上,以下对我有用:

$('#Modal').show().scrollTop(0);
Run Code Online (Sandbox Code Playgroud)

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

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


Nic*_*ick 7

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

$('.modal-body').scrollTop(0);
Run Code Online (Sandbox Code Playgroud)

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

但是,如果您喜欢不那么生涩的运动,请尝试动画路线:

$('.modal-body').animate({scrollTop: 0},400);
Run Code Online (Sandbox Code Playgroud)