问题
$("#contact-form").click(function() {
$('html, body').animate({
scrollTop: $("#contact-section").offset().top
}, 2000);
});
<div class="modal fade" id="saModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>title</h3>
</div>
<div class="modal-body">
text
</div>
<div class="modal-footer">
<button type="button" id="contact-form" class="btn btn-default pull-right glyphicon glyphicon-envelope">Contact</button>
</div>
</div>
</div>
</div>
<div id="contact-section">
<?php require 'contact.php'; ?>
</div>
When I click contact, The bootstrap modal closes as expected but doesn't scroll to contact section, why?
回答1:
Don't use the data-dismiss="modal"
<button type="button" id="contact-form" class="btn btn-default pull-right glyphicon glyphicon-envelope" >Contact</button>
$("#contact-form").click(function() {
$('#myModal').modal('hide');
$('html, body').animate({
scrollTop: $("#contact-section").offset().top
}, 2000);
});
回答2:
My idea, like you can see in the comments, is based on listening for hide.bs.modal event.
My snippet:
$('#saModal').on('hide.bs.modal', function(e) {
if ($('#saModal').attr('ModalXbuttonPressed') != undefined) {
$('#saModal').removeAttr('ModalXbuttonPressed');
return;
}
$('html, body').animate({
scrollTop: $("#contact-section").offset().top
}, 2000);
});
$('#saModal button[class="close"][data-dismiss="modal"]').on('click', function(e) {
$('#saModal').attr('ModalXbuttonPressed', true);
});
$("#contact-form").on('click', function(e) {
$('#saModal').modal('hide');
});
#contact-section {
position: absolute;
top: 500px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#saModal">
Open saModal
</button>
<div class="modal fade" id="saModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>title</h3>
</div>
<div class="modal-body">
text
</div>
<div class="modal-footer">
<button type="button" id="contact-form" class="btn btn-default pull-right glyphicon glyphicon-envelope">Contact</button>
</div>
</div>
</div>
</div>
<div id="contact-section">
<p>contact-section</p>
<p>contact-section</p>
<p>contact-section</p>
<p>contact-section</p>
</div>
来源:https://stackoverflow.com/questions/39614103/close-modal-and-scroll-to-div