onmousemove拖动的时候不触发点击效果

按坐标来判断是否拖动

// 先编写一个跨浏览器绑定事件的对象吧
	var EventUtil = {
	    // 添加绑定事件
	    addHandle: function(element, type, handler) {
	        if(element.addEventListener) {
	            element.addEventListener(type, handler, false);
	        } else if (element.attachEvent) {
	            element.attachEvent("on" + type, handler);
	        } else {
	            element["on" + type] = handler;
	        }
	    },
	    // 移除绑定事件
	    removeHandler: function(element, type, handler) {
	        if(element.removeEventListener) {
	            element.removeEventListener(type, handler, false);
	        } else if (element.detachEvent) {
	            element.detachEvent("on" + type, handler);
	        } else {
	            element["on" + type] = null;
	        }
	    }
	    
	}
	
	//获取元素
	var dv = document.getElementById('floating');
	var x = 0;
	var upx = 0;
	var y = 0;
	var upy = 0;
	var l = 0;
	var t = 0;
	var isDown = false;
	//鼠标按下事件
	dv.onmousedown = function(e) {
	    //获取x坐标和y坐标
	    x = e.clientX;
	    y = e.clientY;

	    //获取左部和顶部的偏移量
	    l = dv.offsetLeft;
	    t = dv.offsetTop;
	    //开关打开
	    isDown = true;
	    //设置样式  
	    dv.style.cursor = 'move';
	}
	//鼠标移动
	window.onmousemove = function(e) {
	    if (isDown == false) {
	        return;
	    }
	    //获取x和y
	    var nx = e.clientX;
	    var ny = e.clientY;
	    //计算移动后的左偏移量和顶部的偏移量
	    var nl = nx - (x - l);
	    var nt = ny - (y - t);

	    dv.style.left = nl + 'px';
	    dv.style.top = nt + 'px';
	}
	//鼠标抬起事件
	dv.onmouseup = function(e) {
		upx = e.clientX;
	    upy = e.clientY;
	    //开关关闭
	    isDown = false;
	    dv.style.cursor = 'default';
	    
	    // 判断是否要跳转
	    EventUtil.addHandle(document.getElementById("floating"), "click", function(){
	        if(isdrag(x,y,upx,upy)){
	        	console.log("拖动过");
	        }else{
	            console.log("没拖动过");
	        }
	    })
	    // 判断是否拖动了,这里我设置了5px,大家可以根据自己来进行修改吧
	    function isdrag(x1, y1, x2 , y2) {
	    	var q=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
	        if( q>= 5) {
	            return true;
	        }
	        return false;
	    }
	}

你可能感兴趣的:(onmousemove拖动的时候不触发点击效果)