js监听滚动条左右滚动

842 阅读1分钟

项目任务,移动端页面做一个可以左右滑动模块,同时监听滚动条的位置,记录位置滑动到对应的位置做一下动画效果,监听左右滚动条的方法还真是一下没有想到,去网上查了一下,改进一点,记录在这里,下面就是代码,具体的动画我没有加上。

HTML代码

<div class="center-swiper" id="swiperId">
    <ul class="swiper-ul">
        <li>
            <img src="../../assets/img/home/gaoxiao.gif" alt="img">
            <h2>Direct and efficient</h2>
            <p>
                Go to the enterprise or headhunting website to screen 2 resumes, cooperate and promote, and
                complete the matching
                process task efficiently through simple interview.
            </p>
        </li>
        <li>
            <img src="../../assets/img/home/zhuanye.gif" alt="img">
            <h2>Major</h2>
            <p>
                The only web3 platform focusing on the integration of C-end, B-end and tasks in the
                blockchain industry on the market
            </p>
        </li>
        <li>
            <img src="../../assets/img/home/hetong.gif" alt="img">
            <h2>Direct and efficient</h2>
            <p>
                Go to the enterprise or headhunting website to screen 2 resumes, cooperate and promote, and
                complete the matching
                process task efficiently through simple interview.
            </p>
        </li>
        <li>
            <img src="../../assets/img/home/jiangli.gif" alt="img">
            <h2>Direct and efficient</h2>
            <p>
                Go to the enterprise or headhunting website to screen 2 resumes, cooperate and promote, and
                complete the matching
                process task efficiently through simple interview.
            </p>
        </li>
    </ul>
</div>

js

function handleScroll() {
    let outDiv = document.getElementById('swiperId') as HTMLElement;

    outDiv.addEventListener('scroll', (e) => {
        
        let scrollLeft = outDiv.scrollLeft
        console.log(scrollLeft);
    })
}

onMounted(() => {
    handleScroll()
})

css

overflow: hidden;
&-swiper {
    overflow-x: auto;

    .swiper-ul {
        display: flex;

        li {
            width: 300px;
            padding: 0 38px 30px;
            text-align: center;
            flex-shrink: 0;

            img {
                width: 206px;
                height: 206px;
                margin-bottom: 64px;
            }

            h2 {
                font-size: 26px;
                font-weight: bold;
                margin-bottom: 24px;
            }

            p {
                font-size: 13px;
                color: #ccc;
                line-height: 22px;
                width: 276px;
                margin: 0 auto;
            }
        }
    }
}