通过HTML+CSS+Javascript实现向下滚动滚动条出现导航栏并出现回到顶部按钮点击按钮回到顶部(一)

回到顶部实例一

效果:默认隐藏导航栏,当滚动条滚到超过300px后导航栏和按钮出现,点击回到顶部按钮回到顶部,并隐藏导航栏和按钮(导航栏和按钮都是固定定位)

<!doctype html>
<html>
<head>
<meta charset="utf-8">

<style>
body {
	margin: 0;
	padding: 0;
	height: 3000px;    /*让滚动条出现*/
}
.DW {
	display: flex;           /*固定定位*/
	justify-content: center;  /*让文字水平居中*/
	align-items: center;      /*让文字垂直居中*/
	width: 100%;
	height: 80px;
	background-color: green;   /*背景颜色绿色*/
	color: aliceblue;
	font-size: 2em;
	transition: top .5s linear;  /*导航栏过渡出现和隐藏*/
	position: fixed;   /* 绝对定位,不管滚动条上下滚动都在相应的位置*/
	top: -80px;        /*隐藏导航栏*/
	left: 0;
}
.goTop {
	width: 50px;
	height: 50px;
	background-color: aquamarine;
	font-size: 20px;
	text-align: center;
	line-height: 25px;
	color: azure;
	position: fixed;    /*固定定位*/
	bottom: 50px;
	right: 50px;
	display: none;   /*隐藏按钮*/
}
	
	.divTop:hover+.topdhl{  /*隐藏的div触发时生效(兄弟关系) ,*/
        /*.divTop:hover .topdhl  (父子关系)*/
	  top: 0px;
	  transition: top .5s linear;  /*导航栏过渡出现和隐藏*/
	}	
	.divdhl:hover{        /*导航栏触发时生效*/
		top: 0px;
	  transition: top .5s linear;  /*导航栏过渡出现和隐藏*/
    }

	.fusu{
	display: flex;           /*固定定位*/
	width: 100%;
	height: 10px;
	left: 0;
	}
  

</style>

</head>

<body >
	<div class="fusu divTop"></div>
<div class="DW topdhl divdhl" id="dhl">导航栏</div>
<buttion class="goTop" id="gotop">回到顶部</buttion>
<script>
  
	//获取导航栏和按量元素
	var topw=document.getElementById("dhl")
	var goTop=document.getElementById("gotop")

	
	//滚动滚动条触发事件
	    window.onscroll=function(){
		  //获取滚动条位置
		var jhlheight=document.documentElement.scrollTop||document.body.scrollTop
		//判断滚动条位置
		if(jhlheight>=300){
		topw.style.top="0px"      //显示滚动条
		goTop.style.display="block"	 //显示按钮
		}else{
		topw.style.top="-80px"     //隐藏滚动条
		goTop.style.display="none"	//隐藏按钮	 
   }
		
	}
	  
	 //点击按钮事件
	  goTop.onclick=function(){
		
		window.scrollTo({     //设置滚动条位置
			top:0,            //回到顶部
			behavior:"smooth"   //平滑过渡
		})
		
	}  
	
	</script>
</body>
</html>

posted @ 2022-01-18 15:57  永恒之月TEL  阅读(549)  评论(0编辑  收藏  举报