最近在学习js,学习的视频来源是妙味js视频,在此首先感谢。
学到BOM这块的时候感触颇多,老师用的例子是“返回顶部”这个效果,虽然是个很老的效果,但是从中获益颇多。现记录如下:首先是HTML代码:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <style> 5 #btn1 {position:fixed; bottom:0; right:0;} 6 </style> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 8 <title>返回顶部效果</title> 9 </head> 10 <body> 11 aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>aaa<br>bbbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br>bbbbbbbbb<br>cccc<br> 12 <input id="btn1" type="button" value="回到顶部" /> 13 </body> 14 </html>
这里对btn1进行简单的样式处理,让它始终位于页面的右下角。
然后是js代码:
1 window.onload=function () 2 { 3 var oBtn=document.getElementById(‘btn1‘); //获取input标签 4 var bSys=true; //用来判断是否是系统定时器导致的滚动 5 var timer=null; //用来停止定时器 6 7 //如何检测用户拖动了滚动条 8 window.onscroll=function () 9 { 10 if(!bSys)//如果不是系统的滚动,也就是说是用户拖动滚动条导致的滚动 11 { 12 clearInterval(timer);//清空定时器 13 } 14 bSys=false; 15 }; 16 17 oBtn.onclick=function () 18 { 19 timer=setInterval(function (){ 20 var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; 21 var iSpeed=Math.floor(-scrollTop/8); 22 23 if(scrollTop==0) 24 { 25 clearInterval(timer); 26 } 27 28 bSys=true; 29 document.documentElement.scrollTop=document.body.scrollTop=scrollTop+iSpeed; 30 }, 30); 31 }; 32 };
时间: 2024-10-13 10:50:19