項(xiàng)目中經(jīng)常會遇到觸發(fā)事件頁面自動滾動到某一位置的情況,一般可以用游標(biāo)實(shí)現(xiàn)贫橙,但也有另一種簡單的實(shí)現(xiàn)思路御吞,利用element.getBoundingClientRect()和window.scrollTo()和window.requestAnimationFrame()
由于是JS控制滾動條,所以我們可以輕松添加動畫效果蛀序,代碼如下
function animateScroll(element,speed) {
let rect=element.getBoundingClientRect();
//獲取元素相對窗口的top值纤控,此處應(yīng)加上窗口本身的偏移
let top=window.pageYOffset+rect.top;
let currentTop=0;
let requestId;
//采用requestAnimationFrame挂捻,平滑動畫
function step(timestamp) {
currentTop+=speed;
if(currentTop<=top){
window.scrollTo(0,currentTop);
requestId=window.requestAnimationFrame(step);
}else{
window.cancelAnimationFrame(requestId);
}
}
window.requestAnimationFrame(step);
}