es6类写一个拖拽功能

es5 托拽功能

 document.getElementById('box').onmousedown = function (e) {
            var startLeft = box.offsetLeft;
            var startTop = box.offsetTop;
            var startX = e.clientX;
            var startY = e.clientY;

            document.onmousemove = function (e) {
                
                var endX = e.clientX;
                var endY = e.clientY;

                var distX = startLeft + (endX - startX);
                var distY = startTop + (endY - startY);

                box.style.left = distX + 'px';
                box.style.top = distY + 'px';
                console.log('正在移动。。。。。')
            }
            document.onmouseup = function () {
                document.onmousemove = null;
            }
        }

es6 class 拖拽功能

class drag{
				constructor(id) {
				    this.div=document.querySelector(id)
					this.disX = 0;
					this.disY = 0;
					this.init();
				}
				init(){
					
					this.div.onmousedown=function(ev){
						
					this.disX = ev.clientX-this.div.offsetLeft;
					this.disY = ev.clientY-this.div.offsetTop;
					
					document.onmousemove = this.fnMove.bind(this);
					document.onmouseup = this.fnUp.bind(this);
					
					return false;
					
					}.bind(this)
				}
				fnMove(ev){
					this.div.style.left=ev.clientX-this.disX+'px';
					this.div.style.top = ev.clientY-this.disY+'px'
				}
				fnUp(){
					document.onmousemove=null;
					document.onmouseup = null;
				}
			}
			
			new drag('#div1')
extends继承
 class ckDrag extends Drag{
		    fnMove(ev){
		        super.fnMove(ev);
		
		        //限制范围
		        if(this.oDiv.offsetLeft<=0){
		            this.oDiv.style.left =0;
		        }
				
		    }
		}
 new ckDrag('#div2');
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值