Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

Problem with scrolldown in slow manner using javascript

I needed JavaScript for automatic scroll down in a smooth/slow manner. I have a form with many radio buttons which is quite similar to survey form.

I used script from the below mentioned link. This link works fine smoothly for scrolling downwards.

But problem comes when you reach the bottom of page and cannot scroll upwards.

I am not so good in JavaScript. Does anyone here has solution or fix to this?

Link to Stack Overflow thread:

Slow down onclick window.scrollBy

function scrollByRate(y, rate) 
{
  //calculate the scroll height
  var scrolling = Math.max( document.getElementsByTagName('html')[0].scrollTop, document.body.scrollTop);

  //save the old value as "static" var
  arguments.callee.tmp = arguments.callee.tmp || scrolling + y;

  //make a little scrolling step
  window.scrollBy(0, (arguments.callee.tmp - scrolling) / rate);

  //are we arrived? if no, keep going recursively, else reset the static var
  if(arguments.callee.tmp - scrolling > 100) setTimeout(function() { scrollByRate(y, rate); }, 10);
  else arguments.callee.tmp = undefined;      
}
<a href="javascript:void(0);" onclick="scrollByRate(350,20)">Scrolling down slowly</a>     

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I can see your approach having a negative impact on performance. It looks like the browser will block until the target scroll destination has been reached.

My suggestion is to use what is out there for smooth scrolling already. The scrollTo method of any scrollable pane (e.g. window object but also a scrollable div for example) has a "behavior" property that you can set to "smooth", e.g.:

window.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

Keep in mind that the compatibility at the time of writing is limited to Chrome, Firefox, Edge and Opera which means you'll have problems on Internet Explorer and Safari (so all Apple products). I myself use a polyfill to get the smooth scrolling back on my application, this one in particular: https://github.com/iamdustan/smoothscroll


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...