/**
* 默认从顶部滚动到指定id(带#)的地方,动画每20ms一次
* @param el 支持以下方式获取el:
* document.querySelector('.类名')
* document.querySelector('#ID')
* document.querySelector('tagname')
*/
const scrollAnimation = function (el, _currentY = 0, gapHeight = 10) {
if (el) {
const _targetY = parseInt(el.offsetTop);
setTimeout(() => {
const needScrollTop = _targetY - _currentY;
_currentY = needScrollTop < 0 ? _currentY - gapHeight : _currentY + gapHeight;
window.scrollTo(0, _currentY);
if (needScrollTop > gapHeight || needScrollTop < -gapHeight) {
scrollAnimation(el, _currentY, gapHeight);
} else {
window.scrollTo(_currentY, _targetY);
}
}, 0);
} else {
console.log('el is null');
}
};