网页返回顶部三种写法

网页返回顶部三种写法:

<h1>头</h1>
<div style="margin-top:1600px;"></div>
<h1 id="button">底部</h1>

方法一(简单版):

<script>
button.onclick = function() {
    if (document.documentElement.scrollTop) {
        document.documentElement.scrollTop = 0
    } else {
        document.body.scrollTop = 0
    }
}
</script>

方法二:

<script>
// 声明变量存放定时器
var t;
// 点击设置定时器
button.onclick = function() {
    // 设置定时器 每隔30ms 改变
    t = setInterval(function() {

        // 如果已经到顶部了 清楚定时器
        if (document.body.scrollTop < 1) {
            clearInterval(t)
            return;
        }
        // 滚动条位置
        document.body.scrollTop -= 30
    }, 30)
}
</script>

方法三(增加了额外条件):

你好啊
<h1 style="width:500px;background: blue;color:#fff;text-align: center;position: fixed;top:0; left: 50%;margin-left:-250px;"></h1>
<div style="margin-top:1600px;"></div>
<h1 id="button" style="width:100px;height: 100px;background: pink;position: fixed; right: 20; bottom: 20; display: none;">底部</h1>

<script>
window.onscroll = function() {
    if (document.body.scrollTop > 300) {
        button.style.display = 'block'
    } else {
        button.style.display = 'none'
    }
}


// 声明变量存放定时器
var t;
// 点击设置定时器
button.onclick = function() {
    // 设置定时器 每隔30ms 改变
    t = setInterval(function() {

        // 如果已经到顶部了 清楚定时器
        if (document.body.scrollTop < 1) {
            clearInterval(t)
            return;
        }
        // 滚动条位置
        document.body.scrollTop -= 30
    }, 30)
}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值