首页 > Web开发 > 详细

js scrollTop到达指定位置!

时间:2014-09-12 17:00:16      阅读:290      评论:0      收藏:0      [点我收藏+]

很早之前就想分享这篇心得, 幸之今天能在这里完成, 好了, 话不多说, 进入正题 :

方法主要利用scrolltop值做运动, 用于到达用户指定的位置(如返回顶部把参数target设置为0即可),处理了多种情况如 scrolltop > 目标值 向上运动 ,等4种情况  , 代码及用法贴上, 

goTo = function(target){
				var scrollT = document.body.scrollTop|| document.documentElement.scrollTop
				if (scrollT >target) {
					var timer = setInterval(function(){
						var scrollT = document.body.scrollTop|| document.documentElement.scrollTop
						var step = Math.floor(-scrollT/6);
						document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
						if(scrollT <= target){
							document.body.scrollTop = document.documentElement.scrollTop = target;
							clearTimeout(timer);
						}
					},20)
				}else if(scrollT == 0){
					var timer = setInterval(function(){
						var scrollT = document.body.scrollTop|| document.documentElement.scrollTop
						var step = Math.floor(300/3*0.7);
						document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
						console.log(scrollT)
						if(scrollT >= target){
							document.body.scrollTop = document.documentElement.scrollTop = target;
							clearTimeout(timer);
						}
					},20)
				}else if(scrollT < target){
					var timer = setInterval(function(){
						var scrollT = document.body.scrollTop|| document.documentElement.scrollTop
						var step = Math.floor(scrollT/6);
						document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
						if(scrollT >= target){
							document.body.scrollTop = document.documentElement.scrollTop = target;
							clearTimeout(timer);
						}
					},20)
				}else if(target == scrollT){
					return false;
				}
			}

  用法 function(target) / / 目前唯一target(目标距离number)  ,

on(goPs,‘click‘,function(){ goTo(2450) }); //运动到scrolltop值为2450地位置,下面也一样, 运动到指定的位置 
on(goJob,‘click‘,function(){ goTo(3373) })
on(goTel,‘click‘,function(){ buffer.goTo(3373) })
on(goMe,‘click‘,function(){ buffer.goTo(1539) })
on(goHome,‘click‘,function(){ buffer.goTo(0) });
on(scrollgoOne,‘click‘,function(){ buffer.goTo(2450) });
on(scrollgoPc,‘click‘,function(){ buffer.goTo(2450) });
on(scrollJob,‘click‘,function(){ buffer.goTo(3373) });
on(scrollMe,‘click‘,function(){ buffer.goTo(1539) });
on(goTop,‘click‘,function(){ buffer.goTo(0) })

 

js scrollTop到达指定位置!

原文:http://www.cnblogs.com/bbyz/p/3968583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!