原生js面向对象实现拖拽小案例

原生js实现拖拽的小案例,欢迎指正!

布局:

<div id="box">

        <div id="ball"></div>

    </div>

样式:

html,body,div{

    margin: 0;

    padding: 0;

}

#box{

    width: 500px;

    height: 500px;

    margin: 50px auto;

    border: 1px solid;

    position: relative;

}

#box>#ball{

    width: 80px;

    height: 80px;

    background: lawngreen;

    position: absolute;

    cursor: pointer;

}

逻辑代码:

// onmousedown\onmouseup\onmousemove拖拽三个事件

//父函数

function Fa(oBox,oBall) {

    this.oBox = oBox;

    this.oBall = oBall;

    var that = this;

    this.oBall.onmousedown = function () {

// event兼容写法

        var event = event || window.event;

// 获取鼠标按下时的x,y坐标

        var x1 = event.clientX;

        var y1 = event.clientY;

// 获取移动是盒子距离上边界、左边界的距离

        var L = that.oBall.offsetLeft;

        var T = that.oBall.offsetTop;

        document.onmousemove = function (event) {

// 鼠标移动后的坐标值

            var x2 = event.clientX;

            var y2 = event.clientY;

// 计算盒子偏移的值等于鼠标移动后坐标-鼠标刚按下值+盒子距离边界偏移量

            var x = x2 - x1 + L;

            var y = y2 - y1 + T;

// 盒子可移动宽度 = 盒子外层盒子宽度-盒子的自身宽度

            var max = that.oBox.clientWidth - that.oBall.offsetWidth;

            var may = that.oBox.clientHeight - that.oBall.offsetHeight;

            if (x < 0) {

                x = 0;

            }

            if (x > max) {

                x = max;

            }

            if (y < 0) {

                y = 0;

            }

            if (y > may) {

                y = may;

            }

// 设置盒子的left值top值

            that.oBall.style.left = x + 'px';

            that.oBall.style.top = y + 'px';

        }

  // 移动事件失效

        document.onmouseup = function () {

            document.onmousemove = null;

            document.onmouseup = null;

        }

    }

}

//子函数

function Son() {

    var oBox = document.getElementById('box');

    var oBall = document.getElementById('ball');

//改变this指向

    Fa.call(this, oBox,oBall)

}

Son();

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容