一、思路
- 一个页面中右下角有一个返回顶部的按钮,当页面向下滑动了一定的距离显示出来,否则隐藏
- 主要是给window添加scroll事件
- 用window.scrollY表示向上拉了多少的距离
- window.scrollY > 200 就显示,否则隐藏
- 给返回到顶部的按钮添加点击事件
- 用scrollTo对象,改变里面的top值,behavior来设置返回顶部的过渡smooth:平稳的
- 写返回顶部的功能
function returnTop(){
scrollTo({
top : 0,
behavior:“smooth”
})
} - 当鼠标经过按钮时,改变背景图片变黑,鼠标移出时也改变,变白
代码演示:
<!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>
</head>
<style>
*{
margin: 0%;
padding: 0;
}
.container{
width: 100%;
height: auto;
background-color: aqua;
}
.nav-top{
width: 100%;
height: 30px;
background-color: aquamarine;
margin: 0% auto;
}
.nav{
width: 100%;
height: 90px;
background-color: rgb(58, 146, 117);
margin: 0% auto;
}
.ad{
width: 100%;
height: 500px;
background-color: rgb(255, 127, 255);
margin: 0% auto;
}
.show{
width: 100%;
height: 400px;
background-color: rgb(127, 255, 174);
margin: 0% auto;
}
.footer{
width: 100%;
height: 400px;
background-color: rgb(127, 178, 255);
margin: 0% auto;
}
.back-top{
width: 50px;
height: 50px;
border-radius: 50%;
position: fixed;
right: 40px;
bottom: 40px;
display: none;
cursor: pointer;
background-image: url(./imgs//返回顶部白.png);
background-size: 50px 50px;
background-repeat: no-repeat;
}
</style>
<body>
<div class="container">
<div class="nav-top">nav-top</div>
<div class="nav">nav</div>
<div class="ad">ad</div>
<div class="show">show</div>
<div class="footer">footer</div>
<div class="back-top"></div>
</div>
<script>
let container = document.querySelector('.container');
let navTop = document.querySelector('.nav-top');
let nav = document.querySelector('.nav');
let show = document.querySelector('.show');
let ad = document.querySelector('.ad');
let footer = document.querySelector('.footer');
let backTop = document.querySelector('.back-top');
// 给Bom的window添加scool事件
window.addEventListener('scroll' , displayReturnTop);
// 写隐藏按钮和显示按钮的功能
function displayReturnTop(e){
console.log(scrollY);
if(window.scrollY > 200){
backTop.style.display = 'block';
}else{
backTop.style.display = 'none';
}
}
// 给backTop添加事件
backTop.addEventListener('click',returnTop);
// 写返回顶部的功能
function returnTop(){
scrollTo({
top : 0,
behavior:"smooth"
})
}
// 当鼠标经过按钮时,改变背景图片
backTop.addEventListener('mouseover',function(){
backTop.style.background = 'url(./imgs//返回顶部黑.png)';
backTop.style.backgroundSize = '50px 50px';
});
backTop.addEventListener('mouseout',function(){
backTop.style.background = 'url(./imgs//返回顶部白.png)';
backTop.style.backgroundSize = '50px 50px';
});
</script>
</body>
</html>
演示结果: