我有类似以下HTML示例的内容
<input type="button" name"btnScroll" value="Scroll" class="scroll-button" />
<div id="builder-items-container">
<div class="item-container scroll-marker">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container scroll-marker">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container scroll-marker">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container scroll-marker">STUFF HERE</div>
</div>
我希望在我的页面上有一个按钮,当我单击它时,将滚动到下一个滚动标记div。我遇到的问题是即使用户手动滚动页面也试图让它工作。就像我怎么能这样做,无论他们在当前页面上的哪个位置,当他们点击我的滚动按钮时,它会转到NEXT出现的“滚动标记”类?
这是我到目前为止所尝试的......
// Scroll Down button
$(document).on('click', '.scroll-button', function(e) {
if ($('.scroll-marker').eq(scrollItem).length) {
var $scrollToItem = $('.scroll-marker').eq(scrollItem);
$('#builder-items-container').animate({
scrollTop: $scrollToItem.offset().top - 150
}, 500);
// Increment our scrollItem var
scrollItem++;
} else {
// No more to scroll to - hide the button
$('.scroll-button').fadeOut(500);
}
});
首次检查长度是我尝试隐藏滚动按钮一旦不再出现“.scroll-marker”滚动到页面的下方。
如果有人能证明我做错了什么,我会非常感激。 谢谢!
答案 0 :(得分:1)
您对if语句的问题..您可以像这样使用它
var scrollItem = 1;
// Scroll Down button
$(document).on('click', '.scroll-button', function(e) {
var $scrollToItem = $('.scroll-marker').eq(scrollItem);
$('body').animate({
scrollTop: $scrollToItem.offset().top - 150
}, 500);
// Increment our scrollItem var
scrollItem++;
if ($('.scroll-marker').eq(scrollItem).length < 1) {
// No more to scroll to - hide the button
$('.scroll-button').fadeOut(500);
scrollItem = 0;
}
});
.scroll-button{
position: fixed;
top : 0;
}
.item-container{
height: 500px;
background: #ff0066;
}
.scroll-marker{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" name"btnScroll" value="Scroll" class="scroll-button" />
<div id="builder-items-container">
<div class="item-container scroll-marker">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container scroll-marker">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container scroll-marker">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container">STUFF HERE</div>
<div class="item-container scroll-marker">STUFF HERE</div>
</div>