拖拽强制刷新记录位置

基本逻辑:根据设置定位的top和left完成拖拽

强制刷新还不动:根据本地存储

html部分        js部分           


export default class Navbar extends Component {
    disX: number = 0
    disY: number = 0
    x: number = 0
    y: number = 0
    num: number = 0
    drag = createRef<HTMLDivElement>()
    DnDown(ev: React.MouseEvent) {
        if (this.drag.current) {
            this.disX = ev.clientX - this.drag.current.getBoundingClientRect().left
            this.disY = ev.clientY - this.drag.current.getBoundingClientRect().top
        }
        document.onmousemove = this.FnMove.bind(this)
        document.onmouseup = this.FnUp.bind(this)

    }
    FnMove(ev: MouseEvent) {
        this.x = ev.clientX - this.disX
        this.y = ev.clientY - this.disY
        if (this.drag.current) {
            this.drag.current.style.top = this.y + "px"
            this.drag.current.style.left = this.x + "px"
        }

    }
    FnUp() {
        let numx = this.x
        let numy = this.y
        console.log(numx,"left",numy,"top")
        localStorage.setItem("numx", JSON.stringify(numx));
        localStorage.setItem("numy", JSON.stringify(numy));
        document.onmousemove = null
        document.onmouseup = null
    }
    componentDidMount() {
        let SessionX = JSON.parse(localStorage.getItem("numx") as "")
        let SessionY = JSON.parse(localStorage.getItem("numy") as "")
        if (this.drag.current) {
            this.drag.current.style.top = SessionY + "px"
            this.drag.current.style.left = SessionX + "px"
        }
        console.log(SessionX, SessionY)
    }
    render() {
        return (
            <nav className="nav-wrapper">
                <div className="drag" onMouseDown={this.DnDown.bind(this)} ref={this.drag}></div>
            </nav>
        )
    }
}

css部分


    .drag{
        position: absolute;
        top: 0;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: aqua;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值