当用户浏览的网页过于长的时候,用户在浏览到网页底部想要在返回顶部需要滚动好几次滚轮才能返回顶部,不仅麻烦,而且用户体验也会很差。现在的大多是页面都会在页面顶部或者是页面的可见区域的某一位置固定一个按钮,点击它可以使页面返回顶部,用户再也不用滚动滚轮了。下面我给大家讲解一下:
html样式
<div class="gotop">返回顶部</div>
css样式
.gotop {
width: 65px;
height: 65px;
background-color: pink;
border-radius: 50%;
position: fixed;
bottom: 100px;
right: 60px;
font-size: 15px;
line-height: 50px;
text-align: center;
display: none;
}
.active {
display: block!important;
}
js样式
var gotop = document.getElementsByClassName("gotop")[0];//获取那个点击盒子
window.onscroll = function () { //window的滚动事件
var scroll_Height = document.documentElement.clientHeight || document.body.clientHeight;//可视区高度
var scroll_Top = document.documentElement.scrollTop || document.body.scrollTop;//滚动条距离父级顶部距离
if (scroll_Top > scroll_Height) {//判断如果滚动条距离父级顶部距离大于可视区高度
gotop.classList.add("active")//显示active样式
}else{
gotop.classList.remove("active")//否则不显示 隐藏
}
}
gotop.onclick=function(){//返回顶部盒子的点击事件
document.documentElement.scrollTop=0;//滚动条距离父级顶部距离为0,就是返回顶部
document.body.scrollTop=0;//兼容
}
将这个代码运用到之前拍的死版中,看一下效果,

这个是一屏的页面

当我们划出一屏的时候出现滚动条,同时出现那个返回顶部的盒子

网友评论