我有一个 Boostrap 模态 jQuery 函数,用于通过 AJAX 调用动态内容。模态框也是可滚动的并且具有固定的高度,因此有人可能在模态框内向下滚动然后关闭它(通过底部的按钮)。
现在的问题是,当打开另一个模式时,它会在前一个模式关闭的同一位置打开,这意味着可能在底部,这会让用户感到困惑。
是否有一种简单的方法可以使模式始终在内容顶部打开(焦点?)?这是我的功能:
function open_box(params)
{
dump(params);
var URL=ajax_url+"/?"+params;
var modal = $('#modal');
modal
.find('.modal-body')
.load(URL, function (responseText, textStatus) {
if ( textStatus === 'success' ||
textStatus === 'notmodified')
{
modal.modal("show");
}
});
}
CSS 是:
.modal-content {
overflow: auto;
}
.modal-dialog {
width: calc(100% - 100px);
margin: 100px auto;
height: 85%;
max-height: calc(100% - 100px);
max-width: 550px;
}
我尝试将 .scrollTop(0)
添加到代码中(就在 find
下方),但没有成功。
最佳答案
尝试使用 HTML 元素的 native 浏览器方法 scrollIntoView()
( Docs )。如果您知道 element
恰好是加载的 HTML 中的顶部元素,则可以在显示弹出窗口后尝试调用 element.scrollIntoView()
。或者您可以确定加载内容的第一个子项并将其滚动到顶部。像这样:
function open_box(params)
{
dump(params);
var URL=ajax_url+"/?"+params;
var modal = $('#modal');
var modalBody = modal.find('.modal-body');
modalBody
.load(URL, function (responseText, textStatus) {
if ( textStatus === 'success' ||
textStatus === 'notmodified')
{
modal.modal("show");
modalBody.get(0).children[0].scrollIntoView();
}
});
}
关于javascript - 如何确保 jQuery 加载的可滚动模态内容始终滚动回顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810815/