我尝试执行以下操作。我创建了这个 fiddle 来展示我想要实现的目标:
https://jsfiddle.net/c4xcb98w/1/
如果用户点击可点击元素链接“点击 6”,它应该滚动到 div .location-wrapper 中的元素。这行得通,但我不明白的是,如果再次单击相同的链接,它会滚动回顶部。
此外,如果我点击 click6,它会向下滚动,然后我点击“click8”,它会再次向上滚动,但不会滚动到第 8 个分区。
有人知道我如何实现吗,如果它已经滚动并且我再次单击同一个触发器它应该什么都不做,如果单击另一个触发器它应该滚动到那个 div?
$('.click_6').click(function(e) {
$('.location-wrapper').animate({
scrollTop: ($("#box_6").offset().top)
}, 'slow');
});
$('.click_8').click(function(e) {
$('.location-wrapper').animate({
scrollTop: ($("#box_8").offset().top)
}, 'slow');
});
#map {
width: 100%;
height: 1000px;
background-color: #000;
}
.location-wrapper {
position: absolute;
top: 20px;
right: 0px;
height: 800px;
overflow-y: scroll;
}
.location-box {
background-color: #fff;
width: 315px;
height: 300px;
margin: 0 0 20px 0;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click_6">click6</div>
<div class="click_8">click8</div>
<div id="map">
</div>
<div class="location-wrapper">
<div class="location-box" id="box_1">#1</div>
<div class="location-box" id="box_2">#2</div>
<div class="location-box" id="box_3">#3</div>
<div class="location-box" id="box_4">#4</div>
<div class="location-box" id="box_5">#5</div>
<div class="location-box" id="box_6">#6</div>
<div class="location-box" id="box_7">#7</div>
<div class="location-box" id="box_8">#8</div>
<div class="location-box" id="box_9">#9</div>
<div class="location-box" id="box_10">#10</div>
<div class="location-box" id="box_11">#11</div>
<div class="location-box" id="box_12">#12</div>
<div class="location-box" id="box_13">#13</div>
<div class="location-box" id="box_14">#14</div>
<div class="location-box" id="box_15">#15</div>
</div>
感谢您的帮助!
最佳答案
.offset()为您提供相对于 document
的坐标,因此您必须考虑包装器的 scrollTop
值。
下面的代码不是最优的,但它会给你一个很好的方向:
$('.click_6').click(function(e) {
$('.location-wrapper').animate({
scrollTop: ($("#box_6").offset().top +
$("#box_6").offsetParent().scrollTop())},
'slow');
});
$('.click_8').click(function(e) {
$('.location-wrapper').animate({
scrollTop: ($("#box_8").offset().top +
$("#box_8").offsetParent().scrollTop())},
'slow');
});
顺便说一句,.position()当您需要相对于父级顶部(包装器)的坐标时更合适。
所以这段代码可能更好:
$('.click_6').click(function(e) {
$('.location-wrapper').animate({
scrollTop: ($("#box_6").poition().top +
$("#box_6").offsetParent().scrollTop())},
'slow');
});
关于javascript - 滚动到 div,防止第二次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356538/