欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > scrollIntoView滚动会把页面偏移换一种滚动方法window.scrollTo解决

scrollIntoView滚动会把页面偏移换一种滚动方法window.scrollTo解决

2025/4/30 1:44:27 来源:https://blog.csdn.net/2302_76925238/article/details/143705233  浏览:    关键词:scrollIntoView滚动会把页面偏移换一种滚动方法window.scrollTo解决
原代码是// 切换滚动到对应位置const selectTab = (val) => {childInstance.value.toggleCollapseNew(val - 1);current_tab.value = val;activeName.value = 'tab' + Number(val - 1);const anchorElement = document.getElementById(`section-${val}`);// document.getElementById(`section-${val}`).scrollIntoView({//   behavior: 'smooth',//   block: 'start',//   inline: 'start',// });};

最终解决代码

const selectTab = (val) => {childInstance.value.toggleCollapseNew(val - 1);current_tab.value = val;activeName.value = 'tab' + val;const anchorElement = document.getElementById(`section-${val}`);if (anchorElement) {const offsetTop = anchorElement.offsetTop;const scrollContainer = document.querySelector('.detail-content-box');(scrollContainer || window).scrollTo({top: scrollContainer ? offsetTop : 600,behavior: 'smooth'});}
};
  • 容器检查(scrollContainer || window) 让代码更紧凑,直接选择 scrollContainerwindow 作为滚动对象。
  • 滚动高度判断:为 scrollContainer 使用 offsetTop,为 window 使用固定高度 16,保持代码简洁的同时确保逻辑不变。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词