JavaScript和jQuery实现回到顶部效果

本文介绍了一种使用HTML、CSS及jQuery实现的平滑滚动回顶部功能。通过监测滚动条位置来显示或隐藏顶部按钮,并利用jQuery动画效果让页面平滑滚动到顶部。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上一大堆了,自己做个笔记。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.content{
	margin:0 auto;
	width:980px;
	height:3600px;	
	background:#000;
}
#top{
	position:fixed;
	left:50%;
	margin-left:500px;
	width:40px;
	height:40px;	
	background:#F00;
	display:none;
	bottom:10px;}
#top:hover{
	background:#0FF;
}
</style>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<!--<script type="text/javascript">
	window.onload=function(){
		
		var isTop=true;
		var top=document.getElementById("top");
		var timer=null;
		var clientHight=document.documentElement.clientHeight;
		
		window.onscroll=function(){
			var osTop=document.documentElement.scrollTop || document.body.scrollTop;
			if(osTop>=clientHight){
				top.style.display="block";
			}else{
				top.style.display="none";	
			}
			if(!isTop){
				clearInterval(timer);
			}
			isTop=True;
		}
		top.onclick=function(){
			timer=setInterval(function(){
				var osTop=document.documentElement.scrollTop || document.body.scrollTop;
				
				var ispeed=Math.floor(-osTop/6);
				document.documentElement.scrollTop=document.body.scrollTop=osTop+ispeed;
				isTop=true;
				if(osTop==0){
					clearInterval(timer);
				}
			},30);	
		}
	}
	
</script>--->
<script>  
$(function(){  
        //当滚动条的位置处于距顶部100像素以下时,跳转链接出现,否则消失  
        $(function () {  
            $(window).scroll(function(){  
                if ($(window).scrollTop()>100){  
                    $("#top").fadeIn(1500);  
                }  
                else  
                {  
                    $("#top").fadeOut(1500);  
                }  
            });  
  
            //当点击跳转链接后,回到页面顶部位置  
  
            $("#top").click(function(){  
                $('body,html').animate({scrollTop:0},300);  
                return false;  
            });  
        });  
    });  
</script>  
<title>无标题文档</title>
</head>
<div class="content"></div>
<div id="top"></div>
<body>
</body>
</html>