更多事件类型请查看:事件类型

鼠标事件

鼠标事件有三个:mousedownmouseupclick
它们三个的执行顺序是:mousedown=》mouseup=>click

mousedownmouseup事件来说,event对象上会有一个button属性,表示按下或释放的是哪个按键。**DOM**为这个**button**属性定义了 3 个值:0 表示鼠标主键、1 表示鼠标中键(通常也是滚轮键)、2 表示鼠标副键。

  1. document.onmousedown = function (event) {
  2. console.log(event.button);
  3. };

拖拽处理边界

  1. elDrag(document.getElementsByClassName("box")[0]);
  2. function elDrag(el) {
  3. var offsetPos = null;
  4. var wWidth = document.documentElement.clientWidth,
  5. wHeight = document.documentElement.clientHeight,
  6. elWidth = parseInt(window.getComputedStyle(el, null).width),
  7. elHeight = parseInt(window.getComputedStyle(el, null).height);
  8. el.addEventListener(
  9. "mousedown",
  10. function (event) {
  11. offsetPos = {
  12. X: event.offsetX,
  13. Y: event.offsetY,
  14. };
  15. document.addEventListener("mousemove", mousemove, false);
  16. document.addEventListener("mouseup", mouseup, false);
  17. },
  18. false
  19. );
  20. function mousemove(event) {
  21. var elLeft = event.pageX - offsetPos.X,
  22. elTop = event.pageY - offsetPos.Y;
  23. // 判断元素是不是在文档的左面
  24. if (elLeft <= 0) {
  25. elLeft = 0;
  26. } else if (elLeft >= wWidth - elWidth) {
  27. // 判断元素是不是在文档的右面
  28. elLeft = wWidth - elWidth;
  29. }
  30. // 判断元素是不是在文档的上面
  31. if (elTop <= 0) {
  32. elTop = 0;
  33. } else if (elTop >= wHeight - elHeight) {
  34. // 判断元素是不是在文档的下面
  35. elTop = wHeight - elHeight;
  36. }
  37. el.style.left = elLeft + "px";
  38. el.style.top = elTop + "px";
  39. }
  40. function mouseup() {
  41. document.removeEventListener("mousemove", mousemove, false);
  42. }
  43. }