元素滚动制可视区域中部
开发中常常遇到要让元素手动滚动到可视化区域。
function scrollToCenter(container, element) {
const containerRect = container.getBoundingClientRect();
const elementRect = element.getBoundingClientRect();
const containerScrollTop = container.scrollTop;
const containerHeight = containerRect.height;
const containerTop = containerRect.top;
const containerBottom = containerRect.bottom;
const elementTop = elementRect.top - containerTop + containerScrollTop;
const elementHeight = elementRect.height;
const scrollTo = elementTop - (containerHeight / 2) + (elementHeight / 2);
container.scrollTo({
top: scrollTo,
behavior: 'smooth' // 若要平滑滚动,可以设置 behavior 为 'smooth'
});
}
使用方法
const container = document.getElementById('your-container-id');
const element = document.getElementById('your-element-id');
scrollToCenter(container, element);