网页返回顶部三种写法:
<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>