ReactHook+Ts实现简易无缝轮播

import React, { useRef, useState } from 'react'
import "./index.less";
export default function Rotation() {
    const tit = [3, 1, 2, 3, 1];
    const box = useRef<HTMLDivElement>(null);
    const [selectIndex, setselectIndex] = useState<number>(1);
    const [flag, setflag] = useState<boolean>(false);
    let disx = 0
    let x = 0
    const changestart = (ev: React.TouchEvent) => {
        disx = ev.changedTouches[0].pageX - x;
    }
    const trend = () => {
        setflag(false);
        if (box.current!.offsetLeft === 0) setselectIndex(3);
        if (selectIndex === tit.length - 1) setselectIndex(1);
    }
    const fnmove = (ev: React.TouchEvent) => {
        x = ev.changedTouches[0].pageX - disx
        box.current!.style.left = selectIndex * -100 + (x / 10) + 'vw';
    }
    const fnend = () => {
        setflag(true);
        if (x > 150 && selectIndex !== 0) setselectIndex(selectIndex - 1);
        if (x < -150 && selectIndex < 4) setselectIndex(selectIndex + 1);
    }
    return (
        <div className='rotation-Box'>
            <div className="rotaion-Box-body" onTransitionEnd={trend} ref={box} style={{ left: selectIndex * -100 + 'vw', transition: flag ? ".3s all" : '' }} onTouchStart={changestart} onTouchMove={fnmove} onTouchEnd={fnend}>
                {tit.map((item, index) => <div className='rotaion-Box-body-item' key={index}>
                    {item}
                </div>)}
            </div>
        </div>
    )
}

less

.rotation-Box {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    position: relative;

    .rotaion-Box-body {
        width: 500vw;
        height: 500px;
        display: flex;
        position: absolute;
        left: 0;
        top: 0;

        .rotaion-Box-body-item {
            width: 100vw;
            height: 500px;
            font-size: 50px;
            text-align: center;
            line-height: 500px;
            background-color: skyblue;

            &:nth-child(1) {
                background-color: pink;
            }

            &:nth-child(4) {
                background-color: pink;
            }

            &:nth-child(2) {
                background-color: orange;
            }

            &:nth-child(5) {
                background-color: orange;
            }
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值