触发顺序
oBtn.onclick = function (e) {
console.log('click')
}
oBtn.onmousedown = function () {
console.log('mousedown')
}
oBtn.onmouseup = function () {
console.log('mouseup')
}
//顺序 mousedown> mouseup> click
封装
/**
* 点击的时候执行点击事件。拖拽的时候执行拖拽
* @param {ELement} elem
* @param {元素点击事件} elemClick
*/
var dragNclick = (function (elem,elemClick) {
var bTime = 0,
eTime = 0,
oPos = [];
function drag(params) {
var x,
y;
addEvent(elem,'mousedown',function (e) {
var e = e || window.event;
bTime = new Date().getTime();
oPos = [getStyle(elem, 'left'), getStyle(elem, 'top')];
x = mousePos(e).x - oPos[0];
y = mousePos(e).y - oPos[1];
addEvent(elem, 'mouseover', mouseMove);
addEvent(elem, 'mouseup', mouseUp);
cancelBubble(e);
preventDefault(e);
})
function mouseMove(e) {
var e = e || window.event;
elem.style.left = mousePos(e).x - x + 'px';
elem.style.top = mousePos(e).y - y + "px";
}
function mouseUp(params) {
var e = e || window.event;
eTime = new Date().getTime();
if (eTime - bTime < 100) {
elem.style.left = oPos[0] + 'px';
elem.style.top = oPos[1] + 'px';
elemClick();
}
eTime = 0;
bTime = 0;
addEvent(document, 'mousemove', mouseMove);
addEvent(document, 'mouseUp', mouseUp);
}
}
drag();
})