拖拽的组件开发,点击抬起title变化

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute;}
#div2{ width:100px; height:100px; background:yellow; position:absolute; left:100px;}
#div3{ width:100px; height:100px; background:blue; position:absolute; left:200px;}
#div4{ width:100px; height:100px; background:green; position:absolute; left:300px;}
</style>
<script>
window.onload = function(){
    
    var d1 = new Drag();
    d1.init({    //配置参数,多个参数的时候用json的形式,变成一个参数,避免了参数加载顺序的问题
        id : 'div1'
    });
    
    var d2 = new Drag();
    d2.init({    //配置参数,多个参数的时候用json的形式,变成一个参数,避免了参数加载顺序的问题
        id : 'div2',
        toDown : function(){
            document.title = 'hello';
            document.body.style.background = 'black';
        }
    });
    
    var d3 = new Drag();
    d3.init({     //配置参数,多个参数的时候用json的形式,变成一个参数,避免了参数加载顺序的问题
        id : 'div3',
        toDown : function(){
            document.title = '妙味';
        },
        toUp : function(){
            document.title = '课堂';
        }
    });
    
    var d4 = new Drag();
    d4.init({      //配置参数,多个参数的时候用json的形式,变成一个参数,避免了参数加载顺序的问题
        id : 'div4',
        toUp : function(){
            document.title = 'beybye';
        }
    });
    
};

function Drag(){
    this.obj = null;
    this.disX = 0;
    this.disY = 0;
    
    this.settings = {   //默认参数,当没有某一项配置参数的时候,即为默认参数的值
        toDown : function(){},
        toUp : function(){}
    };
    
}
Drag.prototype.init = function(opt){  //一般都写opt
    
    var This = this;
    
    this.obj = document.getElementById(opt.id);
    
    extend( this.settings , opt );  //用配置参数去覆盖默认参数
    
    this.obj.onmousedown = function(ev){
        var ev = ev || window.event;
        This.fnDown(ev);
        
        This.settings.toDown();  //调用默认参数的方法
        
        document.onmousemove = function(ev){
            var ev = ev || window.event;
            This.fnMove(ev);
        };
        document.onmouseup = function(){
            This.fnUp();
            
            This.settings.toUp();   //调用默认参数的方法
            
        };
        return false;
    };
    
};

Drag.prototype.fnDown = function(ev){
    this.disX = ev.clientX - this.obj.offsetLeft;
    this.disY = ev.clientY - this.obj.offsetTop;
};
Drag.prototype.fnMove = function(ev){
    this.obj.style.left = ev.clientX - this.disX + 'px';
    this.obj.style.top = ev.clientY - this.disY + 'px';
};
Drag.prototype.fnUp = function(){
    document.onmousemove = null;
    document.onmouseup = null;
};

function extend(obj1,obj2){
    for(var attr in obj2){
        obj1[attr] = obj2[attr];
    }
}


</script>
</head>

<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</body>
</html>

注意事项:

1、

posted @ 2017-12-07 17:05  念念念不忘  阅读(176)  评论(0)    收藏  举报