简体   繁体   English

如何连续自动向上和向下滚动div

[英]how to scroll automatically up and down a div continuously

I am working on html page where i have a div called divContainer . 我正在html页面上工作,我有一个名为divContainer的div。 I want to scroll this div continuously up and down automatically. 我想自动连续上下滚动这个div。 For this I used the following code: 为此我使用了以下代码:

 $(document).ready(function() { var interval = setInterval(function() { if ($("#divContainer").scrollTop() != $('#divContainer')[0].scrollHeight) { $("#divContainer").scrollTop($("#divContainer").scrollTop() + 10); } else { clearInterval(interval); } }, 100); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div id="divContainer" style="height:950px;overflow:auto"></div> 

However this code scrolls the div from top to bottom but not from bottom to top. 但是,此代码将div从上到下滚动,但不是从下到上。 I also want to scroll up and down continuously. 我也想连续上下滚动。 How can I achieve this? 我怎样才能做到这一点?

It can be done simply by storing the direction you're moving and switching when reaching the top/bottom. 只需存储您正在移动的方向并在到达顶部/底部时切换即可。 The easiest way to check if we need to switch is to see if the position has actually changed since the last iteration. 检查是否需要切换的最简单方法是查看自上次迭代后位置是否实际发生了变化。

If you try to scroll to a position by passing in a too small or large number, the position will be set right to the top or bottom respectively. 如果您尝试通过传入太小或大的数字来滚动到某个位置,则该位置将分别设置在顶部或底部。 In this case scrollTop() will return the same number as before, and we'll know it's time to switch direction. 在这种情况下, scrollTop()将返回与之前相同的数字,我们将知道是时候切换方向了。

 var up = false; var lastPosition; var interval = setInterval(function () { var $container = $("#divContainer"); var position = $container.scrollTop(); var height = $container[0].scrollHeight; // If we haven't moved, switch direction if(position === lastPosition) up = !up; lastPosition = position; if (up) { // Going up $container.scrollTop(position - 10); } else { // Going down $container.scrollTop(position + 10); } }, 100); 
 div { border: 1px solid red; width: 200px; height: 200px; overflow: auto; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="divContainer"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM