Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```
- <div class="box">1</div>
- <div class="box">2</div>
- var box = document.getElementsByClassName("box");
- //鼠标按下
- box[0].onmousedown = function(e){
- //兼容IE
- var ev = e || window.event ;//window.event = event
- var divX = ev.offsetX;
- var divY = ev.offsetY;
- //clientX:鼠标距离左边缘的距离
- //offsetX : 是鼠标在元素上的距离
- //var divX = ev.clientX - box.offsetLeft;
- //在鼠标移动中(鼠标按住不动):计算元素距频幕左边缘的距离
- document.onmousemove = function(e){
- var ev = e || event;
- //元素距离屏幕左边缘的距离 = 鼠标距屏幕的距离 - 鼠标据元素左边缘的距离
- var x = ev.clientX - divX;
- var y = ev.clientY - divY;
- //别忘了 去css样式里面加position:absolute;
- //上述所有功能都只是在计算数值,对页面没有任何影响
- //将数值拼接px 作为单位赋给元素的定位属性,才开始影响页面
- box[0].style.left = x + "px";
- box[0].style.top = y + "px";
- //碰撞检测
- //获取移动视图上下左右的位置
- var moveL = box[0].offsetLeft;
- var moveR = box[0].offsetLeft + box[0].offsetWidth;
- var moveT = box[0].offsetTop;
- var moveB = box[0].offsetTop + box[0].offsetHeight;
- //获取被撞视图的上下左右位置
- var hitL = box[1].offsetLeft;
- var hitR = box[1].offsetLeft + box[1].offsetWidth;
- var hitT = box[1].offsetTop;
- var hitB = box[1].offsetTop + box[1].offsetHeight;
- //定义碰撞条件
- var r1 = moveR >= hitL;
- var r2 = moveL <= hitR;
- var r3 = moveT <= hitB;
- var r4 = moveB >= hitT;
- if (r1 && r2 && r3 && r4) {
- document.onmousemove = null;
- }
- }
- //鼠标抬起时,置空移动事件,取消掉元素跟着鼠标移动的功能
- document.onmouseup = function(){
- document.onmousemove = null;
- document.onmousedown = null;
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement