原生JS实现拖拽效果-兼容IE

原生JavaScript实现拖拽效果,要用到三个事件:onmousedown、onmousemove、onmouseup;而且使用有一定的顺序,不能用错;详细的在代码中解释。

基本样式:要让元素绝对定位,脱离文档流,方便拖拽。

#box{
    position:absolute;
    cursor:pointer;
    width:100px;
    height:100px;
    background:#f00;
}

js代码:

 1 window.onload = function(){
 2             var box = document.getElementById('box');
 3             box.οnmοusedοwn=function(e){
 4 
 5                 e = e || window.event;
 6                 //点击时,鼠标距离元素左 上的距离
 7                 var boxLeft = e.clientX - box.offsetLeft;//e.clientX:鼠标距离文档左边的距离  box.offsetLeft:元素距离左边的距离
 8                 var boxTop = e.clientY - box.offsetTop;
 9           //setCapture()/releaseCapture()这两个方式是IE特有的,可以捕获鼠标滑动到窗口外的事件
10                 if(typeof box.setCapture == 'object'){
11                     //IE 
12                   13                     box.οnmοusemοve=mouseMove;
14                     box.οnmοuseup=mouseUp;
15                     box.setCapture();
16                 }else{
17                     window.onmousemove = mouseMove;
18                     window.onmouseup = mouseUp;    
19                 }
20                 
21             
22 
23                 function mouseMove(e){
24                     e = e || window.event;
25                     //计算元素记录文档的左,上的距离
26                     var L = e.clientX - boxLeft;
27                     var T = e.clientY - boxTop;
28 
29                     if(L <= 0){
30                         //超出左边界
31                         L = 0;
32                     }else if(L > document.documentElement.clientWidth - box.offsetWidth){
33                         //超出右边界
34                         L = document.documentElement.clientWidth - box.offsetWidth;
35                     }
36 
37                     if(T <= 0){
38                         //超出上边界
39                         T = 0;
40                     }else if(T > document.documentElement.clientHeight - box.offsetHeight){
41                         //超出下边界
42                         T = document.documentElement.clientHeight - box.offsetHeight;
43                     }
44 
45                     box.style.left = L +"px";
46                     box.style.top = T + "px";
47                 }
48 
49                 function mouseUp(){
50                     if(typeof box.releaseCapture == 'object'){
51                         //IE 
52                         box.releaseCapture();
53                     }
54                     
55                     this.onmousemove = null;
56                     this.onmouseup = null;
57                 }
58 
59             }
60         }

 

转载于:https://www.cnblogs.com/brand-code/p/9755767.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值