美文网首页
useTabList

useTabList

作者: Asuler | 来源:发表于2022-07-25 18:18 被阅读0次

要实现的效果:


image.png

点击后面的选项或者前面的选项,自动居中,自动将选中项弹到中间位置

需要计算出到起点的偏移量
参考:https://github.com/ant-design/ant-design-mobile/blob/master/src/utils/use-tab-list-scroll.ts

根据该文件提取出有用的部分,删除了一些动画效果:

import { bound } from './utils';
const useTabListScroll = (ref, activeIndex, defaultStart = 0) => {
  const container = ref.current;
  if (!container) return;
  if (activeIndex === undefined) return;

  const activeTab = container.children.item(
    activeIndex + defaultStart
  ) as HTMLDivElement
  const activeTabLeft = activeTab.offsetLeft
  const activeTabWidth = activeTab.offsetWidth

  const containerWidth = container.offsetWidth
  const containerScrollWidth = container.scrollWidth
  const maxScrollDistance = containerScrollWidth - containerWidth
  if (maxScrollDistance <= 0) return

  const nextScrollLeft = bound(
    activeTabLeft - (containerWidth - activeTabWidth) / 2,
    0,
    containerScrollWidth - containerWidth
  )
  return nextScrollLeft
}

export default useTabListScroll;

返回的nextScrollLeft就是要手动scroll的位置
bound的文件直接复制即可

export function bound(
  position: number,
  min: number | undefined,
  max: number | undefined
) {
  let ret = position
  if (min !== undefined) {
    ret = Math.max(position, min)
  }
  if (max !== undefined) {
    ret = Math.min(ret, max)
  }
  return ret
}

相关文章

  • useTabList

    要实现的效果: 点击后面的选项或者前面的选项,自动居中,自动将选中项弹到中间位置 需要计算出到起点的偏移量参考:h...

网友评论

      本文标题:useTabList

      本文链接:https://www.haomeiwen.com/subject/hszgirtx.html