CSS实现网页“回到顶部”的效果代码,用CSS hack实现IE6的兼容,功能:
1、和论坛的回顶部悬浮层基本一样,当浏览器的滚动条滚动(>0)时,悬浮层出现,当滚动条滚动为0时隐藏,用到了window.onscroll事件。
2、当浏览器窗口大小发生改变时,悬浮层的位置改变,用到了window.onresize事件,使悬浮层始终位于可视窗口的右下方
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>回到顶部</title>
<style type="text/css">
html{
_overflow:hidden;
}
body{
_overflow:auto;
height:100%;
}
#div{
background:#ccc;
width:400px;
height:1500px;
text-align:center;
}
#returntop{
border:1px #ccc solid;
background:#F30;
width:80px;
height:30px;
position:fixed;
_position:absolute;
line-height:30px;
text-align:center;
top:0px;
left:0px;
display:none;
cursor:pointer;
}
a{
text-decoration:none;
}
</style>
</head>
<body>
<div id="div">这是顶部</div>
<div id="returntop">回顶部</div>
<script type="text/javascript">
var getDiv=document.getElementById('returntop');
getDiv.onclick=function(){
window.scrollTo(0,0);
}
window.onscroll=function(){
if(document.documentElement.scrollTop){
getDiv.style.display="block";
}else if(document.body.scrollTop){
getDiv.style.display="block";
}else{
getDiv.style.display="none";
}
}
function getWinSize(){
var winHeight=window.innerHeight,winWidth=window.innerWidth;
if(document.documentElement.clientHeight){
winHeight=document.documentElement.clientHeight;
winWidth=document.documentElement.clientWidth;
}else{
winHeight=document.body.clientHeight;
winWidth=document.body.clientWidth;
}
var height=winHeight-50;
var width=winWidth-100;
getDiv.style.top=height+"px";
getDiv.style.left=width+"px";
}
getWinSize();
window.onresize=getWinSize;
</script>
</body>
</html>
function goTop() {
$('html, body').animate({scrollTop:0}, 'slow');
}
function goDiv(div) {
var a = $("#"+div).offset().top;
$("html,body").animate({scrollTop:a}, 'slow');
}
function goBottom() {
window.scrollTo(0, document.documentElement.scrollHeight-document.documentElement.clientHeight);
}