锚点scrollIntoView遇到固定头部掩盖
2023-08-17 本文已影响0人
Hasan_hs
解决方案:
参考了JSScrollIntoView插件,运用其核心代码解决此问题。
第一步、方法复制到项目中
/**
*
* @param {*} elem 滚动的元素
* @param {*} options 滚动配置
*/
function scrollIntoView(elem, options) {
options = {
...options,
duration: 1000,
offset: heander.value.clientHeight,
ease: 'ease-out'
}
var scrollOffset = elem.getBoundingClientRect().top - options.offset,
totalScrollOffset = window.scrollY + scrollOffset,
duration = options.duration,
startTime = Date.now(),
distance,
currentScrollPosition;
requestAnimationFrame(function anim() {
currentScrollPosition = window.scrollY;
distance = totalScrollOffset - currentScrollPosition;
var elapsed = Date.now() - startTime;
var progress = Math.min(1, elapsed / duration);
window.scrollTo(0, currentScrollPosition + (distance * progress));
if (progress < 1 && distance !== 0) {
requestAnimationFrame(anim);
}
});
}
第二步、调用方法
scrollIntoView(elem,options)