用javascript实现回到顶部效果

主要知识点:

DOM操作:1,document.getElementById()  根据id获取标签元素

                      2,document.documentElement.scrollTop  滚动条的数值,可读写

事件运用:1,window.onload()     页面加载完毕后触发

                     2,onclick()                   点击后触发

                    3,window.onscroll       滚动条滚动时触发

定时器:   1,setInterval()                 设置定时器,需要传两个参数

                    2,clearInterval()            关闭定时器,需要传一个参数

梳理:获取按钮,加一个事件,获取滚动事件

1,totop.js

window.οnlοad=function(){
	var btn=document.getElementById('totop');
	//timer需要放在最外面
	var timer=null;
	var istop=true;
	//屏幕可视化高度
	var clientHeight=document.documentElement.clientHeight;
	//设置向上滚动时候突然往下翻的事件,注意要加window.onscroll
	window.οnscrοll=function(){
		if(!istop){
			clearInterval(timer);
		}
		istop=false;
		//这里需要再申明一遍high的值,否则获取不到下面已经申明的值,因为Js是从上向下执行代码
		var high=document.documentElement.scrollTop||document.body.scrollTop;
		if(high>=clientHeight){
			btn.style.display='block';
		}else{
			btn.style.display='none';
		}
	}
	btn.οnclick=function(){
		//设置定时器,在30ms之内完成回到顶部的平滑效果
		timer=setInterval(function() {
		//解决各个浏览器的兼容性问题
		//获得的这个high必须写在点击事件里面,因为js是从上往下执行代码
		var high=document.documentElement.scrollTop||document.body.scrollTop;
		//设置向上的速度,由快到慢,并且取负数整,这样可以为0,让定时器关闭
		var speed=Math.floor(-high/6);
		document.documentElement.scrollTop=document.body.scrollTop=high+speed;
		//向上滚动突然停止的变量一开始设为true,并且放在点击事件里面
		istop=true;
		if(high==0){
			clearInterval(timer);
		}
		},30);
	
		
	}
}

2,totop.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="GBK">
		<title></title>
		<link href="//at.alicdn.com/t/font_378311_yebd9tiaj6lgnwmi.css" rel="stylesheet" type="text/css" />
		<!--
			必须要全写
		<script type="text/javascript" src="js/totop.js" />-->
		<script type="text/javascript" src="js/totop.js"></script>
    <style>
    	*{
    		margin: 0;
    		padding: 0;
    	}
    	.main{
    		width: 800px;
    		margin: 0 auto;
    		
    	}
    	.main img{
    		width: 100%;
    	}
    	.totop{
    		position: fixed;
    		width: 48px;
    		height: 48px;
    		background: rgba(0,0,0,0.7);
    		left: 50%;
    		margin-left: 610px;
    		bottom: 10px;
    		z-index: 111111;
    		display: none;
    	}
    	.totop .iconfont{
    		font-size: 45px;
    		color: white;
    	}
    </style>
	</head>
	<body>
		<div class="main"> <img src="img/tao.png"></div>
		<a href="javascript:;"><div class="totop" id="totop"><i class="iconfont icon-huidaodingbu"></i></div></a>
	</body>
</html>



  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值