Slow down onclick window.scrollBy

前提是你 提交于 2021-01-07 07:50:43

问题


I am looking the code for making JavaScript window.scrollBy slower, but I haven't found anything. Could some one please advise me how to animate this type of JavaScript scrolling. And no this link doesn't help me Cross browser JavaScript (not jQuery...) scroll to top animation

Here is JSFiddle

<a  onclick="window.scrollBy(0, 300)">Make me slower</a>

回答1:


Not sure this is the best way to do that but it works fine, is nice and clear:

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;      
}

Then your onclick will be like:

<a href="javascript:void(0);" onclick="scrollByRate(1000,20)">Scrolling down slowly</a>     

Try it here

function scrollByRate(y, rate) {
    var scrolling = Math.max( document.getElementsByTagName('html')[0].scrollTop, document.body.scrollTop);
    arguments.callee.tmp = arguments.callee.tmp || scrolling + y;
    window.scrollBy(0, (arguments.callee.tmp - scrolling) / rate);
    if(arguments.callee.tmp - scrolling > 100) setTimeout(function() { scrollByRate(y, rate); }, 10);
    else arguments.callee.tmp = undefined;      
}
p {
  height:100px;
}
<p>
  <a href="javascript:void(0);" onclick="scrollByRate(500,20)">Scrolling down slowly</a>
</p>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>
<p>f</p>
<p>g</p>
<p>h</p>
<p>i</p>
<p>l</p>

Read here about static var in javascript



来源:https://stackoverflow.com/questions/34433319/slow-down-onclick-window-scrollby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!