滚动条切换进行滚动实现

41 阅读1分钟

自动切换并且滚动

我的解决方案是当节点滚动到滚动滚动条clientHeight能包含的个数以外,就需要进行滚动条的滚动。

const schoolScholl = () => {
    const tabList = document.querySelector('.school-tab') // 滚动父节点
    const tab = document.querySelector('.left-school') // 子节点
    // 获取元素属性
    let secMargin = getComputedStyle(tab); // 用于获取子节点的margin属性
    // 我这里是只设置了margin-bottom 因此只加上了marginBottom
    const height = tab.clientHeight + Number(secMargin.marginBottom.slice(0, -2))
    // 可打印查看具体的值 得出父节点一屏能容纳的最大子节点 样例是一屏最多容纳7个子节点
    scrollNum = Math.floor(tabList.clientHeight / height)
  
    if ((activeIndex.value + 1) > scrollNum) {
        tabList.scrollTo(0, tab.clientHeight * activeIndex.value)
    } else if (activeIndex.value < scrollNum){
        tabList.scrollTo(0,0)
    }
}

QQ录屏20230419152656 -original-original.gif

这样就实现了自动切换并且进行滚动,只需要改动元素节点名称以及其margin就能实现点击切换并且进行滚动了

手动点击切换 进行滚动

QQ录屏20230721113523.gif

具体实现

const scrollDom = document.querySelector('#nums_scroll') // 滚动条容器
const activeDom = document.querySelector('#nums_' + index) // 子元素 
if (!activeDom || !scrollDom) return
// index + 1 走这个
if (preIndex > 0) {
const scrollRate = (1 - activeDom.clientWidth / scrollDom.offsetWidth)
    scrollDom.scrollLeft =  activeDom.offsetLeft - scrollDom.offsetWidth * scrollRate
    // scrollRate 表示子元素占父元素的比例 (1 - 比例) 自行判断
} else {
    // index - 1
    scrollDom.scrollLeft = activeDom.offsetLeft
}