div在父级自由移动不超出范围

html

<template>
    <div>
        bgygyig
        <div id='parent' ref="pondModel">
            <div id="sonModel" ref="sonNode" @mousedown="move"></div>
        </div>
    </div>
</template>

<script>
export default {
    data: () => ({}),
    methods: {
        move(e) {
            let odiv = e.target
            let disX = e.clientX - odiv.offsetLeft
            let disY = e.clientY - odiv.offsetTop
            document.onmousemove = (e) => {
                // console.log(this.$refs.pondModel.offsetHeight)
                //计算元素位置(需要判断临界值)
                let left = e.clientX - disX;
                let top = e.clientY - disY;
                console.log(top, 'top')
                console.log(left, 'left')
                let {
                    offsetHeight: pondModelHeight,
                    offsetWidth: pondModelWidth,
                } = this.$refs.pondModel;
                let {
                    offsetHeight: sonNodeHeight,
                    offsetWidth: sonNodeWidth,
                } = odiv;
                // 左上角(left)
                if (left < 0) {
                    left = 0;
                }
                if (top < 0) {
                    top = 0;
                }
                // 左下角
                if (top > pondModelHeight - sonNodeHeight) {
                    top= pondModelHeight - sonNodeHeight
                    // top = pondModelHeight - sonNodeHeight - sonNodeHeight / 2;
                    // 正常的是 pondModelHeight - sonNodeHeight 但是我的dom 会超出半个所以我这加了半个距离 没找到原因
                }
                if (left > pondModelWidth - sonNodeWidth) {
                    left =pondModelWidth - sonNodeWidth
                    // left = pondModelWidth - sonNodeWidth - sonNodeWidth / 2;
                    // 正常的是 pondModelWidth - sonNodeWidth 但是我的dom 会超出半个所以我这加了半个距离 没找到原因
                }
                odiv.style.left = left + 'px'
                odiv.style.top = top + 'px'
                odiv.style.zIndex = 999

            }
            document.onmouseup = (e) => {
                document.onmousemove = null
                document.onmouseup = null
                odiv.style.zIndex = 1
                odiv = null
            }
        },
    }
}
</script>

<style lang="scss" scoped>
#parent {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    position: relative;

    #sonModel {
        width: 50px;
        height: 50px;
        background: blue;
        position: absolute;
    }
}
</style>

效果图:
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值