在一个横向滚动的容器里面,使高亮的子级容器保持一直在可视范围内
const scrollContainer = document.querySelector('.head-box'); // 父级容器
const activeItem = document.querySelector('.head-title-one'); // 子级容器
const containerRect = scrollContainer.getBoundingClientRect();
const itemRect = activeItem.getBoundingClientRect();
const itemLeft = itemRect.left - containerRect.left;
const itemRight = itemRect.right - containerRect.left;
const containerWidth = containerRect.width;
const scrollLeft = scrollContainer.scrollLeft;
if (itemLeft < 0) {
scrollContainer.scrollTo({ left: scrollLeft + itemLeft, behavior: 'smooth' });
} else if (itemRight > containerWidth) {
scrollContainer.scrollTo({ left: scrollLeft + itemRight - containerWidth, behavior: 'smooth' });
}
本文来自博客园,作者:樱桃树下的约定,转载请注明原文链接:https://www.cnblogs.com/tcyweb/p/18541889

浙公网安备 33010602011771号