鼠标拖拽效果

本文以拖拽div盒子为例
思路分析:要实现拖拽效果,首先应该具备这三个事件 --按下、移动、抬起事件,当鼠标按下时,获取鼠标的坐标,当鼠标移动时,将鼠标的位置坐标给div,鼠标抬起时,清除移动事件
具体实现:

//css样式
<style type="text/css">
			#box{
				position: absolute;
				width: 200px;
				height: 200px;
				background: red;
			}
</style>

html结构
<div id="box"></div>

//js代码
var oBox = document.getElementById("box");
			oBox.onmousedown = function(e){
				var evt = e || event;
				//获取鼠标距离事件源的左边距和上边距
				var _left = evt.offsetX;
				var _top = evt.offsetY;
				
				document.onmousemove = function(e){
					var evt = e || event;
					
					//保持盒子和鼠标位置不变
					var x = evt.clientX - _left;  
					var y = evt.clientY - _top;
					
					//下方的if语句主要是为了不让div拖出窗口区域
					if(x<=0){
						x = 0;
					}
					if(x>=document.documentElement.clientWidth - oBox.offsetWidth){
						x = document.documentElement.clientWidth - oBox.offsetWidth;
					}
					
					if(y<=0){
						y = 0;
					}
					if(y>=document.documentElement.clientHeight - oBox.offsetHeight){
						y = document.documentElement.clientHeight - oBox.offsetHeight;
					}
					
					//设置盒子的位置
					oBox.style.left = x + "px";
					oBox.style.top = y + "px";
				}
				document.onmouseup = function(){
					document.onmousemove = null;    
				}
			}
			

		</script>

第二种使用类实现盒子的拖拽效果
css 代码同上
js代码如下:

class Dialog {
  constructor(text){
    this.text = text
    this.lf,
    this.tp,
    this.x,
    this.y
    this.box,
    this.ismove = false
  }
  init(){ //初始化方法
    this.box = document.getElementById('box')
    this.box.innerText = this.text
    //绑定事件,同时注意this指向问题
    this.box.addEventListener('mousedown',this.mousedown1.bind(this))
    document.addEventListener('mousemove',this.mousemove1.bind(this))
    document.addEventListener('mouseup',this.mouseup1.bind(this))
  }
  mousedown1(e){
    this.ismove = true
    //鼠标距离事件源的上下距离
    this.lf = e.offsetX 
    this.tp = e.offsetY
  }
  mousemove1(e){
    if(this.ismove){
      //盒子位置
      this.x = e.clientX - this.lf 
      this.y = e.clientY - this.tp 
      //边界处理
      if(this.x<=0){
        this.x = 0
      }
      if(this.x>=document.documentElement.clientWidth-this.box.offsetWidth){
        this.x = document.documentElement.clientWidth-this.box.offsetWidth
      }
      if(this.y<=0){
        this.y = 0
      }
      if(this.y>=document.documentElement.clientHeight-this.box.offsetHeight){
        this.y = document.documentElement.clientHeight-this.box.offsetHeight
      }
      this.box.style.left = this.x +'px'
      this.box.style.top = this.y + 'px'
    }
  }
  mouseup1(){
    this.mousemove1 = null
    this.ismove = false
  }
}

var dialog = new Dialog('弹框')
dialog.init()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值