js scrollTop到达指定位置!
很早之前就想分享这篇心得, 幸之今天能在这里完成, 好了, 话不多说, 进入正题 :
方法主要利用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) })