返回顶部效果有多种实现的方式,比如假链接、scroll函数、或者使用scrollTop属性结合setInterval函数来模拟动画效果,这篇教程分别对这三种方法予以实现。
效果图:
相关html代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.fix{
position:fixed;
bottom:0;
right:0;
}
#testin{
background:red;
width:500px;
height:3000px;
}
#test{
background:red;
width:500px;
height:300px;
overflow:scroll;
}
</style>
</head>
<body id="body">
<i id="top" name="top"></i>
<img src="163_1.png">
<img src="163_2.png">
<img src="163_3.png">
<!--<a href="#top"><img class="fix" src="gotop.png"></a>-->
<!-- <a href="javascript:scroll(0,0);"><img class="fix" src="gotop.png"></a>-->
<a href="javascript:;" onClick="goTop()" ><img class="fix" src="gotop.png"></a>
<!--
<div id="test">
<div id="testin"></div>
</div>-->
</body>
</html>
javascript代码:
<script>
//var test=document.getElementById("test");//testin:3000px test:283px(有水平滚动条的缘故,本应该300px)
//alert(test.clientHeight+" "+test.offsetHeight);//
//alert( document.documentElement.clientHeight);
//alert( document.body.clientHeight);
//alert(undefined||3);
var inte;
var scrollHeight;
//获取页面可视区高度:html.clientHeight
var htmlClientHeight = document.documentElement.clientHeight;
//实现返回顶部功能
function minusTop(){
// console.log("document.documentElement.scrollTop:"+document.documentElement.scrollTop);
// console.log("document.body.scrollTop:"+document.body.scrollTop);
var top=document.documentElement.scrollTop || document.body.scrollTop;
console.log(top);
var ispeed = Math.floor(-top / 7);
//scrollBy(0,ispeed);
document.documentElement.scrollTop = top+ispeed;
document.body.scrollTop = top+ispeed;
if(top==0){
// alert("进入清除");
console.log("id:"+inte);
clearInterval(inte);//确保clear的id与返回的id相同
}
}
function goTop(){
inte= setInterval("minusTop()",100);
}
//是否显示返回顶部图标
function isDisplay(){
// console.log("document.documentElement.scrollTop:"+document.documentElement.scrollTop);
// console.log("document.body.scrollTop:"+document.body.scrollTop);
scrollHeight=document.documentElement.scrollTop || document.body.scrollTop;
console.log("scrollHeight"+scrollHeight);
//console.log("htmlClientHeight"+htmlClientHeight);
if(scrollHeight>htmlClientHeight){
document.getElementsByTagName("a")[0].style.display="";
}else{
document.getElementsByTagName("a")[0].style.display="none";
}
}
window.onload=function(){
isDisplay();
window.onscroll=isDisplay;
}
</script>