//編寫一個(gè)scrollToTop函數(shù)
function scrollToTop(el){
if(!el){
el=container;
}
//原始值
let startTop=el.scrollTop;
//最終值
let endTop=0;
//生成一個(gè)動(dòng)畫控制函數(shù)
let scrollAnimationFn=doAnimation(startTop,endTop,300,el);
//執(zhí)行動(dòng)畫,每10ms執(zhí)行一次
let interval=setInterval(()=>{
scrollAnimationFn(interval)
},10)
}
function scrollToElement(containerEl,el){
if(!containerEl){
//父元素
containerEl=container;
}
if(!el){
//獲取到要滾動(dòng)到的元素
let input=document.getElementsByTagName('input')[0];
let id='item'+input.value;
if(!input.value){
id='item'+index;
}
el=document.getElementById(id);
}
let startTop=containerEl.scrollTop;
let endTop=startTop+el.getBoundingClientRect().top;
let scrollAnimationFn=doAnimation(startTop,endTop,300,containerEl);
let interval=setInterval(()=>{
scrollAnimationFn(interval)
},10)
}
function scrollToElement(containerEl,el){
//因?yàn)間etBoundingClientRect().top即為子元素頂部距離父元素頂部的距離,所以這個(gè)值就是子元素相對(duì)于父元素的偏移量,我們傳入這個(gè)值到scrollBy中,即滾動(dòng)到指定元素
containerEl.scrollBy(0,el.getBoundingClientRect().top);
}
滾動(dòng)到底部:
function scrollToBottom(containerEl){
let dy=containerEl.scrollHeight-containerEl.clientHeight;
containerEl.scrollBy(0,dy);
}
滾動(dòng)到頂部
function scrollToTop(containerEl){
let dy=-(containerEl.scrollHeight-containerEl.clientHeight);
containerEl.scrollBy(0,dy);
}
function scrollToBottom(containerEl){
if(!containerEl){
containerEl=container;
}
//dy即為偏移量
let dy=containerEl.scrollHeight-containerEl.clientHeight;
let scrollAnimationFn=doAnimation(dy,300,containerEl);
let interval=setInterval(()=>{
scrollAnimationFn(interval)
},10)
}
function scrollToTop(containerEl){
if(!containerEl){
containerEl=container;
}
//dy即為偏移量
let dy=-(containerEl.scrollHeight-containerEl.clientHeight);
let scrollAnimationFn=doAnimation(dy,300,containerEl);
let interval=setInterval(()=>{
scrollAnimationFn(interval)
},10)
}
function scrollToElement(containerEl,el){
if(!containerEl){
containerEl=container;
}
if(!el){
let input=document.getElementsByTagName('input')[0];
let id='item'+input.value;
if(!input.value){
id='item'+index;
}
el=document.getElementById(id);
}
//dy即為偏移量
let dy=el.getBoundingClientRect().top;
let scrollAnimationFn=doAnimation(dy,300,containerEl);
let interval=setInterval(()=>{
scrollAnimationFn(interval)
},10)
}
/**
* @description:
* @param {type}
* @return:
*/
function doAnimation(dy,duration,el){
//使用閉包保存變量exe_dy和step等變量(每次動(dòng)畫滾動(dòng)的距離)
let exe_dy=0;//已經(jīng)執(zhí)行的偏移量
let step=dy/(duration/10);
return function(interval){
exe_dy+=step;
if(Math.abs(exe_dy)>=Math.abs(dy)){
clearInterval(interval);
}
el.scrollBy(0,step);
}
}