javascript Back to Top Effects
- 2021-07-06 10:04:38
- OfStack
The example of this article shares the effect of javascript returning to the top for your reference. The specific contents are as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title> Back to Top Effect (Native js ) </title>
<style type="text/css">
body{
margin: 0;
}
.bg{
width: 1022px;
margin: 0 auto;
}
.btn{
display: none;
width: 75px;
height: 75px;
background:url(../images/ Web page top Small icon (back to the top) / Back to the top -085.png) no-repeat left top;
position: fixed;
left: 50%;
margin-left: 530px;
bottom: 10px;
text-indent: -9999px;
outline: none;
}
.btn:hover{
background-position: 0 -75px;
}
</style>
<script>
var timer=null;
var isScroll=true;
//1.2 Structure oScroll Function
function oScroll(){
var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1 Rolling height , Compatible
var oSpeed=Math.ceil(osTop/4);// Rolling speed
document.documentElement.scrollTop=document.body.scrollTop=osTop-oSpeed;
if(osTop==0){// Judge to reach the top , Cleaning timer
clearInterval(timer);
}
isScroll=true;
}
window.onload=function() {
var obtn=document.getElementById('btn');// Get button element
var clientHeight=document.documentElement.clientHeight||document.body.clientHeight;
// 1. Click the Back button event
btn.onclick=function(){// Bind click events to buttons
timer=setInterval(oScroll,50);
}
window.onscroll=function() {
var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1 Rolling height , Compatible
if (osTop>clientHeight) {
btn.style.display="block";
}else{
btn.style.display="none";
}
if(!isScroll){
clearInterval(timer);
}
isScroll=false;
}
}
</script>
</head>
<body>
<div class="bg">
<img src="../images/jz.jpg">
</div>
<a href="javascript:void(0);" title=" Back to the top " id="btn" class="btn"> Back to the top </a>
</body>
</html>
The above is the whole content of this article, hoping to help everyone learn JavaScript programming.