页面从底部跳转到顶部

在我们平常浏览网页的时候,会发现有些网页的底部会有按钮可以跳转到顶部,下面用js给大家介绍一个方法:
css样式,把div高度设大,就会出现滚动条

<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			div{
				position: relative;
				width: 500px;
				height: 3000px;
				background-color: antiquewhite;
				margin:auto;
				transition: 2s;
			}
			button{
				position: fixed;
				bottom: 20px;
				right: 20px;
			}
		</style>

布局

		<div>
		</div>
		<button type="button" >返回顶部</button>

js:

// 返回顶部			
	let oBtn=document.querySelector("button");
	var speed=20;
	oBtn.onclick=function(){
		time=setInterval(function(){
			document.documentElement.scrollTop-=speed;
			if(document.documentElement.scrollTop<=1000){//当滚动条距离顶部1000时,让速度变慢
				speed=5;
				
			}
			if(document.documentElement.scrollTop<=0){
				clearInterval(time);
				
			}
		})
		
	}

这里主要用到的是一个scrollTop方法

猜你喜欢

转载自blog.csdn.net/weixin_43853424/article/details/86071795
今日推荐