点击返回顶部

关键在于通过document.documentElement.scrollTop获取到鼠标向上滑动的距离,根据距离做一系列的操作

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	*{
		margin:0;
		padding:0;
	}
	.content {
		height: 2000px;
	}
	.goTop {
		width: 100px;
		height: 100px;
		background-color: #bbb;
		text-align: center;
		/*行内元素垂直居中,line-height=行高*/
		line-height: 100px;
		position: fixed;
		bottom: 100px;
		right: 20px;

		display: none;

	}
	</style>
</head>
<body>
<div class="content">
	<div>
		<h2>返回首屏</h2>
		<div class="goTop">返回</div>
	</div>
</div>
<script type="text/javascript">
// 实现逻辑:1.当用户滑动滚动条,到达400px,返回按钮显示,返之小于400时,隐藏
// 2.点击,返回按钮时,滚动条恢复原位
// 让谁进行滚动 body html
let goTop = document.getElementsByClassName('goTop')[0];
window.onscroll = function() {
	// document.documentElement以一个元素对象返回文档元素
	// 小测试:两个值或运算||,取最大值
	let res = document.documentElement.scrollTop;
	console.log('res',res);
	console.info(res)
	if(res>=400){
		goTop.style.display = 'block';
	}else{
		goTop.style.display = 'none';
	}	
}
goTop.onclick = function(){
	 document.documentElement.scrollTop = 0;
}


</script>
	
</body>
</html>
posted @ 2021-08-07 15:05  黑蛋的博客  阅读(61)  评论(0编辑  收藏  举报