<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>改变滚动条样式,适用于webkit内核的浏览器,平滑返回顶部功能实现</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body{
background-color: #2a3542;
color: #797979;
overflow: hidden;
}
.scroll-bar{
position: relative;
width: 1000px;
height: 800px;
border: 1px solid #666666;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
text-align: center;
overflow: auto;
}
/* 定义滚动条的宽度 */
::-webkit-scrollbar{
width: 5px;
}
/* 滚动条的滑轨背景色以及圆角度数 */
::-webkit-scrollbar-track{
background-color: #666666;
/* -webkit-border-radius: 6px; */
}
/* 滚动条滚动轨迹纵向背景 */
::-webkit-scrollbar-thumb:vertical{
height: 10px;
background-color: #FFAA33;
-webkit-border-radius: 6px;
}
/* 滚动条滚动轨迹横向背景 */
::-webkit-scrollbar-thumb:horizontal{
width: 5px;
background-color: #FFAA33;
-webkit-border-radius: 6px;
}
/* 鼠标滑过滚动条背景色 */
::-webkit-scrollbar-thumb:hover{
background-color: #CC6600;
}
.tdTop{
position: fixed;
right: 20px;
bottom: -80px;
z-index: 999;
}
.tdTop .btn{
width: 50px;
height: 50px;
margin-bottom: 1px;
cursor: pointer;
position: relative;
border-radius: 50%;
}
.tdTop .btn-top{
background: url("gotop.png");
}
.tdTop .btn-top:hover{
background-position: 50px 50px;
}
</style>
</head>
<body>
<div class="scroll-bar" id="scroll-bar"></div>
<div id="tdTopBox" class="tdTop">
<div id="btn_top" class="btn btn-top" style="display: none;"></div>
</div>
<script type="text/javascript">
var tdTopBoxObj = document.getElementById("tdTopBox"),
scrollObj = document.getElementById("scroll-bar"),
showHideObj = document.getElementById("btn_top"),
speed = 25; /* 滚动速度,值越大,滚动速度越慢 */
/* 向页面添加内容,用于让滚动条出现 */
for(var i=0;i<100;i++){
var p_node = document.createElement("p");
p_node.innerHTML = "第 "+i+" 个";
scrollObj.appendChild(p_node);
}
/* 监听滚动事件,用于判断是否显示隐藏返回顶部按钮 */
scrollObj.onscroll = function(){
if(scrollObj.scrollTop > 100){
if(showHideObj.style.display!="block"){
showHideObj.style.display = "block";
animateToShow(-80);
}
}else{
if(showHideObj.style.display!="none"){
animateToHide(25);
}
}
}
/* 显示返回顶部按钮动画 */
function animateToShow(x){
x = x+5;
setTimeout(function(){
tdTopBoxObj.style.bottom = x+"px";
if(x < 25){
animateToShow(x);
}
},5);
}
/* 隐藏返回顶部按钮动画 */
function animateToHide(x){
x = x-5;
setTimeout(function(){
tdTopBoxObj.style.bottom = x+"px";
if(x > -80){
animateToHide(x);
}else{
showHideObj.style.display = "none";
}
},5);
}
/* 绑定事件,让滚动条返回顶部 */
tdTopBoxObj.onclick = function(){
goTop(scrollObj.scrollTop);
};
function goTop(x){
if(x > 100){
x = x-100;
setTimeout(function(){
scrollObj.scrollTop = x;
goTop(x);
},speed);
}else{
scrollObj.scrollTop = 0;
}
};
</script>
</body>
</html>
下面是返回顶部按钮图片: