我想做的是在屏幕右下角引入一个按钮,用户可以单击该按钮滚动到下一个“部分”div。一旦到达 html 中的最后一个 div,它应该循环回到第一个 divsection
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>
我采取了稍微不同的方法来回答你的问题。我将代码更改为:
1)用a初始化第一个元素.selected
class.
2) 在寻呼机上单击,移动.selected
将指定元素向上或向下分类。
3) 将类移动到新选择的元素后,滚动到该元素(具有类的元素.selected
).
这是结果的小提琴:
http://jsfiddle.net/rt13qnmm/ http://jsfiddle.net/rt13qnmm/
我们现在要做的就是管理位置.selected
类并根据其新位置滚动。
所有动画均使用自定义函数完成scrollToSelected(offset)
// Perform animation to the '.selected' class
function scrollToSelected(offset){
$('html,body').stop(true).animate({
scrollTop:$('.selected').offset().top + offset
}, 'slow');
}
(这可以通过删除硬编码来进一步解耦.selected
jQuery 选择器并将其作为参数传递给函数,从而允许您滚动到整个站点的任何元素)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)