1、返回顶部:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
button{
position: fixed;
right: 30px;
bottom: 100px;
/* display: none; */
}
/* .action{
display: block;
} */
</style>
</head>
<body>
<div class="content"></div>
<button >返回顶部</button>
<script>
var content = document.querySelector('.content');
var btn = document.querySelector("button");
btn.style.display = 'none'
for(var i = 0;i<100;i++){
var h1 = document.createElement('h1');
h1.innerHTML = '文本内容' + i;
content.appendChild(h1)
}
var Y = 0; // 记录滚动条滚动位置
// 1:如何实现监听滚动条的位置
window.onscroll = function(e){
// console.log(scrollY);
Y = scrollY
if(scrollY>400){
// alert('位置到了')
btn.style.display = 'block'
}else{
btn.style.display = 'none'
}
}
btn.onclick = function(){
// 如何实现指定滚动条滚动到哪一个位置
// 如何实现过度返回顶部?
console.log(Y);
// 如何随时获取滚动条,当前滚动的高度
var move = Y;;
var timer = setInterval(function(){
move = move - 50
if(move<=0){
move = 0;
scrollTo(0,move);
clearInterval(timer)
}
console.log(move);
scrollTo(0,move);
},1)
}
</script>
<!--
1: 当滚动条滚动到某个位置时候;显示返回顶部阿牛
2:小于该位置时候按钮隐藏