纯js实现拖拽组件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽的组件开发</title>
<style>
*{margin:0;padding:0;}
.container > div{position:absolute;}
.container .box:first-child{background-color: #0AAFD8;left:200px;}
.container .box:last-child{background-color: #BB6688;left:400px;}
</style>
</head>
<body>
<div class="container">
<div class="box" id="boxOne"></div>
<div class="box" id="boxTwo"></div>
</div>

<script>
    window.onload = function(){
        var oBoxOne = new Drag();
        oBoxOne.init('boxOne',200,200,function(){
            document.title = 'Hello';
        });

        var oBoxTwo = new Drag();
        oBoxTwo.init('boxTwo',200,200,function(){
            document.title = 'World!';
        });
    }
    function Drag(){
        this.obj = null;
        this.disX = 0;
        this.disY = 0;
        this.width =  0;
        this.height = 0;
    }

    Drag.prototype.init = function(id,w,h,callback){
        var That = this;

        this.obj = document.getElementById(id);

        // 设置块box宽度高度
        this.obj.style.cssText = 'width:'+w+'px;height:'+h+'px;';
        this.width = w;
        this.height = h;

        this.obj.onmousedown = function(ev){
            var ev = ev || window.event;
            That.fnMouseDown(ev);

            document.onmousemove = function(ev){
                var ev = ev || window.event;
                That.fnMouseMove(ev);
            }

            document.onmouseup = function(ev){
                var ev = ev || window.event;
                That.fnMouseUp(ev);
                callback();
            }
        }

    }

    //鼠标上的按钮被按下触发
    Drag.prototype.fnMouseDown = function(ev){
        this.disX = ev.clientX - this.obj.offsetLeft;
        this.disY = ev.clientY - this.obj.offsetTop;
    }

    //鼠标按下后,松开时触发
    Drag.prototype.fnMouseUp = function(){
        document.onmousemove = null;
        document.onmouseup = null;
    }

    //鼠标移动时触发
    Drag.prototype.fnMouseMove = function(ev){
        var winW = (document.documentElement.clientWidth || document.body.clientWidth) - this.width,
            winH = (document.documentElement.clientHeight || document.body.clientHeight) - this.height,
            tgL = ev.clientX - this.disX,
            tgT = ev.clientY - this.disY;

            // 处理拖拽边界
            if(tgL >= 0){
                tgL = tgL > winW ? winW : tgL;
            }else{
                tgL = 0;
            }
            if(tgT >= 0){
                tgT = tgT > winH ? winH : tgT;
            }else{
                tgT = 0;
            }

        this.obj.style.left = tgL + 'px';
        this.obj.style.top = tgT +'px';

    }
</script>

</body>
</html>

赞(2)
前端开发者 » 纯js实现拖拽组件
64K

评论 抢沙发

评论前必须登录!