scrollTop回到顶部详解

scrollTop回到顶部详解

1. scrollTop

scrollTop/scrollLeft:滚动条卷去的高度/宽度,这两个属性是可读可写的,它们有边界值(最小值为0,有最大值)。若设置超过边界值,不会生效,它们依旧是边界值
* 最小值:0
* 最大值:ele.scrollHeight - ele.clientHeight

2. document.documentElement与document.body的区别

2. 1为什么要兼容?

当获取或设置scrollTop值是,要用兼容写法:document.documentElement[attr] || document.body[attr]
* document代表的是整个文档(对于一个网页来说包括整个网页结构),document.documentElement是整个文档节点树的根节点,在网页中即html标签;
* document.body是整个文档DOM节点树里的body节点,网页中即为body标签元素。
* 在文档使用了DTD时,document.body.scrollTop的值为0,此时需要使用document.documentElement.scrollTop来获取滚动条滚过的长度;
* 在未使用DTD定义文档时,使用document.body.scrollTop获取值。

2. 2DTD 是什么?
  • DTD告诉浏览器当前文档用的是什么标记语言,然后浏览器才能正确的根据W3C标准解析文档代码。
  • DTD 在html文档中定义DTD就是通过!doctype定义

3. 回到顶部详解

3.1 分析

  • 总时间(duration):500ms
  • 频率(interval): 多长时间走一步 10ms
  • 总距离(target): 当前位置(scrollTop)-目标位置(0)
  • 步长(step):每一步走的距离 target/duration –> 每1ms走的距离 * interval

3.2 代码

// css
a {
    width: 50px;
    height: 50px;
    position: fixed;
    bottom: 100px;
    right: 50px;
    border-radius: 50%;
    background: beige;
    text-align: center;
    line-height: 50px;
    color: #666;
    text-decoration: none;
    display: none;
}

// html
<a id="link" href="javascript:;">顶部</a>
// js
var goTop = document.getElementById('link');
function setDisplay() {
  curTop = document.documentElement.scrollTop || document.body.scrollTop;
  curHeight = document.documentElement.clientHeight || document.body.clientHeight;
  goTop.style.display = curTop > curHeight ? 'block' : 'none';
}
window.onscroll = setDisplay;
goTop.onclick = function () {
  // 点击按钮,返回顶部,此时让按钮消失
  this.style.display = 'none'; // 只设置display不行,往上走的时候,window.onscroll事件会触发,还是到顶部才能隐藏,需要清除onscroll事件
  window.onscroll = null;
  var duration = 500, interval = 10, target = document.documentElement.scrollTop || document.body.scrollTop,
    step = (target / duration) * interval;
  var timer = setInterval(function () {
    var curTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (curTop === 0) {
      window.clearInterval(timer);
      window.onscroll = setDisplay; // 回到顶部时,再给window.onscroll重新绑定方法,待下一次执行
      return;
    }
    curTop -= step;
    document.documentElement.scrollTop = curTop;
    document.body.scrollTop = curTop;
  }, interval);
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值