思路:
1、使用position中的fixed属性值,将其固定在窗口的右下角;
2、该定display默认值为none,当滚动条下滑到一定长度后显示按钮;
3、点击按钮实现回到顶部;
4、回到顶部后按钮再次隐藏。
核心:改变滚动条滚动的长度。
一、首先完成HTML、CSS代码
<div id="backtop">
<p>Top</p>
</div>
CSS代码可以使用内联样式,也可以使用外联样式,但不建议使用行内样式。
#backtop{
background: whitesmoke;
width: 60px;
height: 60px;
position: fixed; /*fixed属性可以将div固定在指定位置*/
z-index: 2;
right: 20px;
bottom: 20px;
}
#backtop p{
line-height: 60px;
text-align: center;
color: burlywood;
}
二、JS
- 隐藏按钮
//获取对象
var back = document.getElementById('backtop')
back.style.display ='none'
//检查滚动条,是否显示返回顶部的按钮
document.onscroll = function(){
//只有滚动条滚动的长度大于100px的时候显示按钮,其他情况则隐藏按钮
if (document.documentElement.scrollTop > 100){
back.style.display = 'block'
}else{
back.style.display = 'none'
}
}
- 鼠标移入事件
//鼠标移入的效果
back.onmouseover = function (){
back.style.background = 'white'
back.firstElementChild.innerText = '^';
back.style.fontSize = 23 + 'px'
back.style.cursor = 'pointer' //移入后改变鼠标形状
}
- 鼠标移出事件
//鼠标移出的效果
back.onmouseover = function (){
back.style.background = 'whitesmoke'
back.firstElementChild.innerText = 'Top';
back.style.fontSize = 16 + 'px'
}
按钮的某些属性在鼠标移入时已经改变,需要在鼠标移出之后再次设置属性。
- 按钮的点击事件
//点击事件
back.onclick = function(){
document.documentElement.scrollTop = 0
}
点击事件只需要将滚动条的滚动长度设置为0,就可以实现回到顶部的功能。
完整代码Github:(案例未上传,可以关注获取完整代码)
网友评论