很早之前就想分享這篇心得, 幸之今天能在這里完成, 好了, 話不多說, 進入正題 :
方法主要利用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) })
