<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回到顶部scrollTop</title>
<style type="text/css">
#button{width: 50px;height: 50px;border-radius: 50%;background: #000;opacity: 0.4;position: fixed;bottom: 30px;right: 30px;display: none;}
.content{background:-webkit-gradient(linear, 0 0, 0 100%, from(green), to(yellow));height: 2000px;width: 100%;}
</style>
</head>
<body>
<div id="button"></div>
<div class="content"></div>
<script>
// 回到顶部scrollTop
// 总时间(duration):500ms
//频率(interval):多长时间走一步 10ms
//总距离(target):当前的位置(当前的scrollTop值)目标位置0;
// 步长(step):每一次走的距离 target/duration * interval 每一次走的距离
var button = document.getElementById("button");
window.onscroll = computedDisplay;
function computedDisplay(){
var curTop = document.documentElement.scrollTop || document.body.scrollTop;
var curHeight = document.documentElement.clientHeight || document.body.clientHeight;
button.style.display = curTop>curHeight?"block":"none";
}
button.onclick = function(){
this.style.display = "none";
window.onscroll = null;
var duration = 500,interval = 10,target = document.documentElement.scrollTop || document.body.scrollTop;
var step = (target/duration) * interval;
var timer = window.setInterval(function(){
var curTop = document.documentElement.scrollTop || document.body.scrollTop;
if(curTop ===0){
window.clearInterval(timer);
window.onscroll = computedDisplay;//动画结束后方法重新绑定
return;
}
curTop -=step;
document.documentElement.scrollTop = curTop;
document.body.scrollTop = curTop;
},interval);
}
</script>
</body>
</html>
js点击按钮滚动到顶部
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- <!DOCTYPE html> *{margin: 0;padding: 0;}.test{border...
- 只有一个ScrollView的时候 我们在使用App的时候,经常会看到这样的效果,当我们点击状态栏的时候,我们已经...
- 背景 现在有许多 app 都有这个需求, 点击 statusBar, tableView/collectionvi...