jquery - 动画 jquery 在同一个单击按钮上上下滚动
问题描述
当单击相同的按钮但在不同的滚动区域上时,我正在尝试为滚动设置动画,例如:
- 如果滚动为 0 或小于 300 像素并且单击了按钮,则将滚动动画到指定元素。
- 如果滚动超过 300 像素,并且单击按钮,则将滚动动画设置到页面顶部。
但到目前为止,第一个状态正在工作,但第二个状态,如果单击按钮将滚动到第二部分的顶部,而不是页面(正文)的顶部。
$(window).scroll(function() {
if ($(this).scrollTop() > 300) {
// if scrolling more than 300px add classes active and up
$('#scroll-button').addClass('active up').removeClass('down');
} else {
// is no scroll or less than 300px, remove class active and add class down
$('#scroll-button').removeClass('active up').addClass('down');
}
});
// is no scroll or less than 300px and #scroll-button.down is clicked, animate scrolling to the next element
$('.down').on('click', function() {
$('html,body').animate({
scrollTop: $("#second").offset().top
},
600);
return false;
});
// if scrolling more than 300px and #scroll-button.up button is clicked, animate scroll to the top of the page
$('.up').on('click', function() {
$('html, body').animate({
scrollTop: 0
}, 600);
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first" class="section"><button id="scroll-button" class="down" type="button">Click Me!</button></div>
<div id="second" class="section">Hi</div>
jsfiddle:http: //jsfiddle.net/uky5fs1d/2/
解决方案
谢谢你们@DBS 和@AlwaysHelping,根据那篇文章,我已经更改了我的代码,现在正在工作。
// GO TO TOP
$(window).scroll(function () {
if ($(this).scrollTop() > 300) {
// if scrolling more than 300px add classes active and up
$('#scroll-button').addClass('active up').removeClass('down');
} else {
// is no scroll or less than 300px, remove class active and add class down
$('#scroll-button').removeClass('active up').addClass('down');
}
});
$(document).on('click', '#scroll-button', function(){
if ($('#scroll-button').hasClass('down')){
$('html,body').animate({
scrollTop: $("#second").offset().top},
600);
return false;
} else {
$('html, body').animate({
scrollTop: 0
}, 600);
return false;
}
});
工作小提琴:http: //jsfiddle.net/uky5fs1d/3/
推荐阅读
- sql - 通过 Laravel Query Build 转换 sql
- sql - 查询获取 SSRS 报告参数和下拉选项缓慢
- sql - 用“street”动态选择表中的所有地址行,并用“st”替换
- javascript - Angular 双向数据绑定和监视父组件的变化
- java - 如何在进度条上显示进度(改装下载)
- typescript - 做什么
意思是? - selenium - 使用 Selenium (Webdriver) 测试 Merge
- wordpress - 自定义 WP 块库
- ios - 使用 UIView 作为导航栏的缺点
- python - 无法弄清楚如何使用 Scrapy “抓取”具有类名的标签