更改滚动条位置 [英] Changing Scrollbar Position

查看:380
本文介绍了更改滚动条位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户到达某个网页向下滚动时,是否可以更改滚动条位置?例如,一旦你到达页面的一半,滚动条就会自动移回到顶部。

Is it possible to change the scrollbar position when the user reaches a certain point scrolling down a web page? For example once you reached half way down down the page the scrollbar would move automatically back to the top.

推荐答案

你可以计算出来使用 onscroll 事件滚动条当前位置的百分比,如果达到可以使用 scrollTo function:

You can calculate the percentage of the current position of the scrollbar using the onscroll event, and if it reaches the 50 % the scroll position can be set to the top of the page with the scrollTo function:

window.onload = function () { 
  window.onscroll = function () { 
    var doc = document.body, 
    scrollPosition = doc.scrollTop,
    pageSize = (doc.scrollHeight - doc.clientHeight),
    percentageScrolled = Math.floor((scrollPosition / pageSize) * 100); 

     if (percentageScrolled >= 50){ // if the percentage is >= 50, scroll to top
       window.scrollTo(0,0); 
     } 
   }; 
};

您可以查看我的示例这里

这篇关于更改滚动条位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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