原代码是// 切换滚动到对应位置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)
让代码更紧凑,直接选择scrollContainer
或window
作为滚动对象。 - 滚动高度判断:为
scrollContainer
使用offsetTop
,为window
使用固定高度16
,保持代码简洁的同时确保逻辑不变。