【发布时间】:2015-09-24 05:36:21
【问题描述】:
我要做的是在屏幕右下角引入一个按钮,用户可以单击该按钮滚动到下一个“部分”div。一旦他们到达 html 中的最后一个 div,它应该循环回到第一个 section div。
我提出的解决方案是,当页面最初加载时,它会收集一个类名为“section”的项目数组,然后当用户点击按钮时,它会在它们之间循环滚动页面。这可能吗?
这是我尝试使用的滚动 JavaScript 的链接。
HTML
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<script>
$(document).ready(function(){
$('.btnPrev').click(function() {
var target;
$(".section").each(function(i, element) {
target = $(element).offset().top - 20;
if (target - 40 > $(document).scrollTop()) {
return false; // break
}
});
$("html, body").animate({scrollTop: target}, 700);
});
$('.btnNext').click(function() {
var target;
$(".section").each(function(i, element) {
target = $(element).offset().top - 20;
if (target - 40 > $(document).scrollTop()) {
return false; // break
}
});
$("html, body").animate({scrollTop: target}, 700);
});
});
</script>
<style type="text/css">
html {background-color: rgb(40,40,40);}
.section {background-color:lightblue;margin: 40px 100px; padding:20px; height:300px;}
.rowA {background-color:lightgreen;}
/*Scroll Buttons*/
.btnScroll {position: fixed; background-color: rgba(0,0,0,.5); width:40px; height:40px; text-align:center; line-height:40px; color:white; border-radius:4px;}
.btnScroll:hover {background-color: rgba(255,255,255,.2); cursor:pointer;}
.btnScroll:active {background-color: rgba(255,255,255,.5); cursor:pointer; selection:none;}
.btnPrev {bottom: 70px; right: 20px;}
.btnNext {bottom: 20px; right: 20px;}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
<script src="rats.js"></script>
<div class="section rowA">Content Here</div>
<div class="section rowB">Content Here</div>
<div class="section rowA">Content Here</div>
<div class="section rowB">Content Here</div>
<div class="section rowA">Content Here</div>
<div class="section rowB">Content Here</div>
<div class="section rowA">Content Here</div>
<div class="btnScroll btnPrev noselect">↑</div>
<div class="btnScroll btnNext noselect">↓</div>
</body>
</html>
【问题讨论】:
-
不知何故,您的 jquery 根本与您的 html 无关。尽管页面上没有单个
a-tag,但您将点击事件附加到链接标签。