触发顺序

    1. oBtn.onclick = function (e) {
    2. console.log('click')
    3. }
    4. oBtn.onmousedown = function () {
    5. console.log('mousedown')
    6. }
    7. oBtn.onmouseup = function () {
    8. console.log('mouseup')
    9. }
    10. //顺序 mousedown> mouseup> click

    封装

    1. /**
    2. * 点击的时候执行点击事件。拖拽的时候执行拖拽
    3. * @param {ELement} elem
    4. * @param {元素点击事件} elemClick
    5. */
    6. var dragNclick = (function (elem,elemClick) {
    7. var bTime = 0,
    8. eTime = 0,
    9. oPos = [];
    10. function drag(params) {
    11. var x,
    12. y;
    13. addEvent(elem,'mousedown',function (e) {
    14. var e = e || window.event;
    15. bTime = new Date().getTime();
    16. oPos = [getStyle(elem, 'left'), getStyle(elem, 'top')];
    17. x = mousePos(e).x - oPos[0];
    18. y = mousePos(e).y - oPos[1];
    19. addEvent(elem, 'mouseover', mouseMove);
    20. addEvent(elem, 'mouseup', mouseUp);
    21. cancelBubble(e);
    22. preventDefault(e);
    23. })
    24. function mouseMove(e) {
    25. var e = e || window.event;
    26. elem.style.left = mousePos(e).x - x + 'px';
    27. elem.style.top = mousePos(e).y - y + "px";
    28. }
    29. function mouseUp(params) {
    30. var e = e || window.event;
    31. eTime = new Date().getTime();
    32. if (eTime - bTime < 100) {
    33. elem.style.left = oPos[0] + 'px';
    34. elem.style.top = oPos[1] + 'px';
    35. elemClick();
    36. }
    37. eTime = 0;
    38. bTime = 0;
    39. addEvent(document, 'mousemove', mouseMove);
    40. addEvent(document, 'mouseUp', mouseUp);
    41. }
    42. }
    43. drag();
    44. })