js实现简单的拖拽效果

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title></title>
</head>
<style>
body{
    position: relative;
}
#a{
    width:100px;
    height:100px;
    background: yellow;
    position: absolute;
}
</style>
<script>
window.onload= function(){
    new Drag('a');
    
}
window.onload = function(){
    var oA = document.getElementById("a");
    oA.onmousedown = function(ev){
        var ev = ev || event;
        var disX = ev.clientX - oA.offsetLeft;
        var disY = ev.clientY - oA.offsetTop;

        document.onmousemove = function(ev){
            var ev = ev || event;
            oA.style.left = ev.clientX - disX + "px";
            oA.style.top = ev.clientY - disY + "px";
        };
        document.onmouseup = function(){
            document.onmousemove = null;
            document.onmouseup = null;

        };

        return false;
    }
}
</script>
<body>
    <div id="a">
    </div>
</body>
</html>

面向对象版:

function Drag(id){
    var _this = this;
    this.disX = 0;
    this.disY = 0;
    this.oDiv = document.getElementById(id);

    this.oDiv.onmousedown = function(ev){
        _this.fnDown(ev);
        return false;
    };
}

Drag.prototype.fnDown = function(ev){
    var _this = this;
    var oEvent = ev || event;
    this.disX = oEvent.clientX - this.oDiv.offsetLeft;
    this.disY = oEvent.clientY - this.oDiv.offsetTop;

    document.onmousemove = function(ev){
        _this.fnMove(ev);
    };
    document.onmouseup = function(){
        _this.fnUp();
    };
};

Drag.prototype.fnMove = function(ev){
    var oEvent = ev || event;
    this.oDiv.style.left = oEvent.clientX - this.disX + "px";
    this.oDiv.style.top = oEvent.clientY - this.disY + "px";
};

Drag.prototype.fnUp = function(){
    document.onmousemove = null;
    document.onmouseup = null;
};

 

posted @ 2013-11-07 16:10  Oo坚oO  阅读(179)  评论(0编辑  收藏  举报