减慢 onclick window.scrollBy [英] Slow down onclick window.scrollBy

查看:54
本文介绍了减慢 onclick window.scrollBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使 JavaScript window.scrollBy 变慢的代码,但我什么也没找到.有人可以告诉我如何为这种类型的 JavaScript 滚动设置动画.没有这个链接对我没有帮助 跨浏览器 JavaScript(不是jQuery...) 滚动到顶部动画

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

这里是 JSFiddle

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

推荐答案

不确定这是最好的方法,但效果很好,很清晰:

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>     

在这里试试

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>

阅读这里关于javascript中的静态变量

Read here about static var in javascript

这篇关于减慢 onclick window.scrollBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆