要实现的效果:
![](https://img.haomeiwen.com/i7852092/32715cbc3e833e42.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
}
网友评论