[英]Scroll up a div when scrolling down is finished using one button
我在堆栈溢出时搜索了解决方案,但没有找到。 这就是为什么我要提出解决方案。 我不擅长jQuery。
我在一个网站上工作,该网站具有使用按钮向下滚动div的功能。 而我做到了。 现在,我想当某人通过单击向下滚动按钮到达div底部时,该按钮变成一个向上滚动按钮,并将他/她带到div顶部。
下面是我的向下滚动代码。
<div id="testi-scroll">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
</div>
<button class="scroll-up"><img src="gotop-arrow.png" alt="gotop-arrow" /></button>
<script>
var scrolled=0;
jQuery(document).ready(function(){
jQuery(".scroll-dwn").on("click" ,function(){
scrolled=scrolled+150;
jQuery("#testi-scroll").animate({
scrollTop: scrolled
});
});
});
</script>
如果没有您的HTML,很难给您一个具体的答案,但这是一个建议:使用.toggleClass
切换类,并检查该类是否存在以找出是否向上或向下滚动:
<script>
jQuery(document).ready(function(){
jQuery(".scroll-btn").on('click', function(){
jQuery(this).toggleClass('scroll-down')
if ( jQuery(this).hasClass('scroll-down') ) {
$('html, body').animate({
scrollTop: $("#element").offset().top
}, 2000);
} else {
$('html, body').animate({
scrollTop: $("#element").offset().top
}, 2000);
}
});
});
</script>
我不建议将scrolled
变量初始化为零并在用户单击按钮时进行更新,因为这种方法无法解决用户单击并拖动滚动条而不使用按钮的情况。
这是我解决问题的方法。 你可以在这里找到jsfiddle
jQuery(document).ready(function(){
jQuery(".scroll-btn").on('click', function(){
if($(this).hasClass("scrollup")){
$("#testi-scroll").animate({
scrollTop: 0
}, 200);
$(this).removeClass("scrollup");
$(this).text("Scroll Down");
} else {
var scrolled = $("#testi-scroll")[0].scrollTop;
scrolled += 150;
$("#testi-scroll").animate({
scrollTop: scrolled
}, 200);
var scrollHeight = $("#testi-scroll")[0].scrollHeight;
var divHeight = $("#testi-scroll").height();
if(scrolled >= scrollHeight- divHeight){
$(this).addClass("scrollup");
$(this).text("Scroll Up");
}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.