首页 > Web开发 > 详细

js 拖拽实现面向对象

时间:2018-05-13 18:43:15      阅读:180      评论:0      收藏:0      [点我收藏+]
// JavaScript Document

    /*构造函数*/
    function Drag(id){
        this.disX = 0;
        this.disY = 0;
        this.oDiv = document.getElementsByTagName(id)[0];
        var _this = this;
        this.oDiv.onmousedown = function(ev){
            _this.fnDown(ev);
            return false;
        };
    }
    Drag.prototype.fnDown = function(ev){
        var oEvent = ev || event;
        this.disX = oEvent.clientX - this.oDiv.offsetLeft;
        this.disY = oEvent.clientY - this.oDiv.offsetTop;
        var _this = this;
        document.onmouseover = function(ev){
            _this.fnMove(ev);
        };
        document.onmouseup = function(){
            _this.fnUp(ev);
        };
    }
    Drag.prototype.fnMove = function(ev){
        var ev = ev || event;        
        this.oDiv.style.left = ev.clientX - this.disX+‘px‘;
        this.oDiv.style.top = ev.clientY - this.disY+‘px‘;
   }
   Drag.prototype.fnUp = function(){
        document.onmouseover = document.onmouseup = null;
   }
// JavaScript Document

function LimateDrag(id){
    Drag.call(this,id); //继承属性
}

//继承方法
for(var i in Drag.prototype){
    LimateDrag.prototype[i] = Drag.prototype[i]
}

LimateDrag.prototype.fnMove = function(ev){
        var ev = ev || event;
        var l = ev.clientX - this.disX;
        var t = ev.clientY - this.disY;

        if(l < 0){
            l = 0;
        }else if(l >= document.documentElement.clientWidth-this.oDiv.offsetWidth ){
            l = document.documentElement.clientWidth-this.oDiv.offsetWidth;
        }
        
        if(t < 0){
            t = 0;
        }else if(t >= document.documentElement.clientHeight-this.oDiv.offsetHeight){
            t = document.documentElement.clientHeight-this.oDiv.offsetHeight;
        }
        
        this.oDiv.style.left = l+‘px‘;
        this.oDiv.style.top = t+‘px‘;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
    div{width:100px;height:100px;background:red;position:absolute;left:0;top:0;}
</style>
<script src =‘Drag.js‘></script>
<script src =‘LimateDrag.js‘></script>

<script>
    window.onload = function(){
        new LimateDrag(div);
    };
</script>
</head>

<body>
<div></div>
</body>
</html>

 

js 拖拽实现面向对象

原文:https://www.cnblogs.com/moon-yyl/p/9032882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!