面向对象写拖拽事件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>拖拽</title>
        <style type="text/css">
            div{
                width: 200px;
                height: 200px;
                background: red;
                position: absolute;
                top: 100px;
                left: 100px;
                cursor: move;
            }
        </style>
    </head>
    <body>
        <div id="box"></div>
    </body>
    <script type="text/javascript">

        /*var box=document.getElementById('box');
        box.onmousedown=function(e){
            var dix=e.clientX-this.offsetLeft;
            var diy=e.clientY-this.offsetTop;
            e.preventDefault();
            document.onmousemove=function(e){
                var dix2=e.clientX-dix;
                var diy2=e.clientY-diy;
                box.style.left=dix2+'px';
                box.style.top=diy2+'px';
            };
            document.onmouseup=function(){
                document.onmousedown=document.onmousemove=null;
            }
        }*/

        /*
         *面向对象方法
         */

        /*变形:
        1.尽量不要有函数的嵌套。
        2.可以有全局变量;
        3.把onload里面不是赋值的语句放到函数中;

        修改:
        1.全局变量就是属性;
        2.函数就是方法;
        3.onload中创建对象实例;
        4.改this的指向
        */

        //构造函数
        function Tab(id){
            this.box=document.getElementById(id);
            this.dix=0;
            this.diy=0;
            this.inset();
        }

        //原型
        Tab.prototype.inset=function(){
            var _this=this;
            this.box.onmousedown=function(e){
                var e=e||window.event;
                _this.down(e);
            };
        }

        Tab.prototype.down=function(e){ 
            var _this=this;
            this.dix=e.clientX-this.box.offsetLeft;
            this.diy=e.clientY-this.box.offsetTop;
//          e.preventDefault();
            document.onmousemove = function(ev){
                var e=ev||window.event;
                _this.move(e);
            };
            document.onmouseup=function(){
                _this.up();
            }
        }

        Tab.prototype.move=function(e){
            this.box.style.left=e.clientX-this.dix+'px';
            this.box.style.top=e.clientY-this.diy+'px';
        }

        Tab.prototype.up=function(){
            document.onmousedown=document.onmousemove=null;
        }
        //实例
        var b=new Tab('box');
        b.inset();
    </script>
</html>

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值