我有一个打开模态窗口的链接 我想打开模态窗口并滚动到其中的特定DIV。
HTML:
<a href="#teamMembers" data-toggle="modal" class="teamMemebrScroll1">read more</a>
<a href="#teamMembers" data-toggle="modal" class="teamMemebrScroll2">read more</a>
<a href="#teamMembers" data-toggle="modal" class="teamMemebrScroll3">read more</a>
<div class="portfolio-modal modal fade" id="teamMembers" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="container" data-id="teamMemebrScroll1">....</div>
<div class="container" data-id="teamMemebrScroll2">....</div>
<div class="container" data-id="teamMemebrScroll3">....</div>
</div>
JS:
// scroll to team member 2
jQuery(document).ready(function ($) {
$(".teamMemebrScroll2").click(function (event) {
event.preventDefault();
$('html,body').animate({ scrollTop: $(this.hash).offset().top }, 1000);
});
});
模态正确打开,但它总是滚动到顶部。
答案 0 :(得分:2)
$('html,body')
,但是当模态打开时您想要滚动到模态内的内容,因此它应该是$('modalselector')
click
个事件,并且可以通过在模态触发按钮中添加附加data attributes
来BS modal event function来实现相同的结果。< / LI>
醇>
在模态触发按钮中进行了一些更改,添加了数据属性data-id
,并且在您尝试时无需click
事件。
<a href="#teamMembers" data-toggle="modal" data-id="teamMemebrScroll1" class="teamMemebrScroll1">read more</a>
<a href="#teamMembers" data-toggle="modal" data-id="teamMemebrScroll2" class="teamMemebrScroll2">read more</a>
<a href="#teamMembers" data-toggle="modal" data-id="teamMemebrScroll3" class="teamMemebrScroll3">read more</a>
和BS模态事件函数
$('#teamMembers').on('shown.bs.modal', function (e) {
//alert('modal shown');
var id = $(e.relatedTarget).data('id'); // <--fetch modal button data-id when modal shown
});
因为您已经将数据属性data-id
添加到模态
<div class="container" data-id="teamMemebrScroll1">....</div>
<div class="container" data-id="teamMemebrScroll2">....</div>
<div class="container" data-id="teamMemebrScroll3">....</div>
所以只需要在模态中匹配模态按钮data-id
和元素data-id
,并在模态打开时滚动到它
$(document).ready(function () {
$('#teamMembers').on('shown.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id'); // Modal button data-id
var team = $('.container[data-id="' + id + '"]'); // Element data-id with match the Modal button data-id
$(this).animate({ // Modal
scrollTop: team.offset().top // Scroll to the element
}, 1000);
});
});
如果你想使用相同的方法更多地控制滚动,回过头来我找到了一个非常小的脚本,它做得更好。请检查以下
答案 1 :(得分:0)
尝试打开窗口时,首先要做的就是链接。 此链接转到特定的div&#34; teamMembers&#34;
<a href="#TeamMembers" ... />
在您的窗口上使用Php,如下所示:
<?php
header('Location: #TeamMembers');
?>