javascript - 重复单击时单击事件中的jQuery scrollTop无法正常工作
问题描述
在我的 HTML 中,我<div>
在lastText
另一个<div>
. 我需要单击一个按钮并滚动到lastText
. 当我单击该按钮时,它会滚动到 ,<div>
但是当我再次单击它时,它会滚动到顶部和底部之间的某个位置。当我滚动到中间的某个地方并单击按钮时,它不会滚动到lastText
. 所以基本上滚动只有在我从最顶部开始滚动时才能正常工作。当lastText
从<div>
. 我该如何解决这个问题?
这是代码:
解决方案
你可以做的是使用这样的函数scrollTop: $('WhereYouWantToScroll').offset().top
所以你的例子可以很容易地通过在 div 的顶部和底部之间切换来完成
var isTop = true;
function test() {
if(isTop){
$('#scrollTest').animate({
scrollTop: $('#lastText').offset().top
}, 1000);
}
else{
$('#scrollTest').animate({
scrollTop: $('#scrollTest').offset().top + -10
}, 1000);
}
isTop = !isTop;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="scrollTest" style="height : 100px; overflow : auto;">
1 - Long Div Scrolling text <br/>
2 - Long Div Scrolling text <br/>
3 - Long Div Scrolling text <br/>
4 - Long Div Scrolling text <br/>
5 - Long Div Scrolling text <br/>
6 - Long Div Scrolling text <br/>
7 - Long Div Scrolling text <br/>
8 - Long Div Scrolling text <br/>
9 - Long Div Scrolling text <br/>
10 - Long Div Scrolling text <br/>
11 - Long Div Scrolling text <br/>
12 - Long Div Scrolling text <br/>
13 - Long Div Scrolling text <br/>
14 - Long Div Scrolling text <br/>
15 - Long Div Scrolling text <br/>
16 - Long Div Scrolling text <br/>
17 - Long Div Scrolling text <br/>
<div id="lastText">last</div>
</div>
<button type="button" onclick="test()">scroll down</button>
推荐阅读
- gzip - 如何测试您的 REST API 服务是否支持 gzip 数据?
- sql - PostgreSQL中是否有一个函数可以计算列之间的字符串匹配(按行)
- r - R从S3下载文件
- swiftui - SwiftUI:真实设备显示异步流的奇怪行为,而模拟器完美运行
- c# - 为什么我的查询值在不应该发生变化时会发生变化?
- javascript - 如何将 Django-Template 变量发送到 Morris.Line 数据变量?
- condor - 如何帮助 condor 找到它应该在作业中执行的文件?
- python - 检查 GROUP BY 和列之间的值
- r - 在 R 中使用 reshape 将数据框从长更改为宽。未定义的列错误
- javascript - 如何定期重新渲染反应组件