当打开模态框时,为了让用户在交互时更加专注,我们通常会禁止页面滚动。这时,可以使用jQuery对body元素进行操作来实现禁止滚动的效果。下面,我将分享如何用jQuery防止Body在打开模态时滚动的攻略。
步骤一:阻止默认事件
为了禁止body滚动,我们需要阻止浏览器在滚动时的默认事件。我们可以在打开模态框的同时,给body元素添加加阻止默认事件的CSS样式,代码如下:
$('body').css('overflow', 'hidden');
这样,当模态框打开时,用户就无法通过滚动页面来浏览其他内容了。
步骤二:解除阻止
当用户关闭模态框时,我们需要解除对body的滚动限制,以便用户可以继续滚动页面。我们可以在关闭模态框的同时,去掉添加的CSS样式,代码如下:
$('body').removeAttr('style');
这样,当模态框关闭时,用户就可以恢复正常的浏览体验了。
示例如下
下面是两个具体的示例,分别演示如何在打开/关闭模态框时,防止body的滚动。代码中使用的是Bootstrap框架的Modal组件。
示例一:使用Bootstrap组件
<!-- HTML代码 -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
打开模态框
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">模态框标题</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>模态框内容...</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭模态框</button>
<button type="button" class="btn btn-primary">保存更改</button>
</div>
</div>
</div>
</div>
<!-- JS代码 -->
$('#exampleModal').on('show.bs.modal', function () {
$('body').css('overflow', 'hidden');
})
$('#exampleModal').on('hidden.bs.modal', function () {
$('body').removeAttr('style');
})
示例二:自定义模态框
<!-- HTML代码 -->
<button id="openModal" type="button">打开模态框</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>模态框内容...</p>
</div>
</div>
<!-- JS代码 -->
$('#openModal').on('click', function() {
$('body').css('overflow', 'hidden');
$('#myModal').show();
});
$('#myModal .close').on('click', function() {
$('body').removeAttr('style');
$('#myModal').hide();
});
以上是防止body在打开模态时滚动的完整攻略,希望对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:如何用jQuery防止Body在打开模态时滚动 - Python技术站