在一个横向滚动的容器里面,使高亮的子级容器保持一直在可视范围内

      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' });
      }

 

posted @ 2024-11-12 14:49  樱桃树下的约定  阅读(4)  评论(0编辑  收藏  举报
返回顶端