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

导读:本篇文章讲解 div在父级自由移动不超出范围,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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>

效果图:
div在父级自由移动不超出范围 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/79815.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!