JS实现点击回到顶部并改变导航栏高度

实现思路

HTML部分给导航栏及回到顶部css设置为固定定位fixed,通过js的onscroll滚动事件获取页面滚动距离进行判断,当滚动距离大于10时,显示回到顶部按钮,改变导航栏高度。当点击回到顶部按钮时,调用定时器方法,改变scrollTop的值回到顶部。

HTML

head导入向上箭头链接

<link href="//netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">

body里面代码

	<!-- 导航栏start -->
	<div class="header" id="header-top">
		<ul>
			<li>吃惊</li>
			<li>卧槽</li>
			<li>我的天</li>
			<li>HTML</li>
			<li>JavaScript</li>
		</ul>
	</div>
	<!-- 导航栏end -->
	<!-- 回到顶部图标start -->
	<!-- 通过导入font-awesome图标库展示向上箭头-->
	<div class="icon" id="icon">
		<i class="fa fa-chevron-up fa-3x" aria-hidden="true"></i>
	</div>
	<!-- 回到顶部图标end -->

CSS

   *{
		margin: 0;
		padding: 0;
	}
	body{
		height: 1500px;
	}
	.header{
		width: 100%;
		height: 100px;
		position: fixed;
		top: 0;
		left: 0;
		background-color: #00FFFF;
		transition: height 0.3s;
	}
	.header.fixed{
		height: 50px;
		box-shadow: 0 0 1px 0 rgba(0,0,0,.3),
		0 0 6px 2px rgba(0,0,0,.15);
	}
	.header li{
		float: left;
		margin-left: 50px;
		margin-top: 15px;
		list-style: none;
	}
	.icon{
		background-color: rgba(0,0,0,0.2);
		position:fixed;
		bottom: 50px;
		right: 30px;
		
	}

Js代码

<script type="text/javascript">
	var headerTop=document.getElementById("header-top");
	var icon=document.getElementById("icon");
	
	window.onscroll=function(){
		var scrolltop=document.documentElement.scrollTop;
		console.log(scrolltop);
		//console.log(bodytop);
		if(scrolltop>10){
			headerTop.className='header fixed';
			icon.style.display="block";
			
		}
		else{
			headerTop.className='header';
			icon.style.display="none";
		}
	}
	//点击向上按钮,回到顶部实现
	var timerId=null;
	icon.onclick=function(){
		if(timerId){
			clearInterval(timerId);
			timerId=null;
		}
		timerId=setInterval(function(){
			//设置每次移动的距离
			var  step=10;
			//设置头顶距离
			var target=0;
			//获取当前位置
			var current=document.documentElement.scrollTop;
			if(current>target){
				step=-Math.abs(step);
			}
			//判断目标是否到达位置
			if(Math.abs(current-target)<=Math.abs(step)){
				clearInterval(timerId);
				document.documentElement.scrollTop=target;
				return;
			}
			current+=step;
			document.documentElement.scrollTop=current;
		},5)
	}
</script>

实现效果

实现前
实现前,回到顶部不显示,高度不变
实现后
实现后,回到顶部图片显示,点击可回到顶部,导航栏高度变小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值