当前位置:   article > 正文

原生js鼠标事件onmousedown、onmousemove、onmouseup实现窗口的拖拽_js onmousedown

js onmousedown
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. <style>
  7. body {
  8. margin: 0;
  9. }
  10. #nav {
  11. height: 30px;
  12. line-height: 30px;
  13. background-color: darkblue;
  14. padding-left: 20px;
  15. }
  16. #nav a {
  17. color: #fff;
  18. text-decoration: none;
  19. }
  20. #box {
  21. width: 400px;
  22. height: 300px;
  23. border: 1px solid #000;
  24. position: absolute;
  25. left: 40%;
  26. top: 35%;
  27. }
  28. #hd {
  29. background-color: darkblue;
  30. height: 30px;
  31. line-height: 30px;
  32. color: #fff;
  33. padding-left: 10px;
  34. cursor: move;
  35. }
  36. #hd span {
  37. cursor: pointer;
  38. float: right;
  39. }
  40. </style>
  41. <script src="js/common.js"></script>
  42. </head>
  43. <body>
  44. <div id="nav"><a href="javascript:void(0)">注册信息</a></div>
  45. <div id="box">
  46. <div id="hd">注册信息(可以拖拽)<span id="box_close">【关闭】</span></div>
  47. <div id="bd"></div>
  48. </div>
  49. <script>
  50. var box = document.getElementById('box');
  51. var hd = document.getElementById('hd');
  52. var positionX, positionY, offsetX, offsetY, mouseX, mouseY;
  53. hd.onmousedown = function (e) {
  54. e = e || window.event;
  55. // 鼠标在盒子中的位置 = 鼠标按下时在页面中的坐标 - 盒子在页面中的偏移
  56. mouseX = getPage(e).pageX - box.offsetLeft;
  57. mouseY = getPage(e).pageY - box.offsetTop;
  58. // 鼠标移动的时候,盒子在页面中的偏移 = 鼠标当前位置-鼠标在盒子中的位置
  59. box.onmousemove = function (e) {
  60. e = e || window.event;
  61. boxX = getPage(e).pageX - mouseX;
  62. boxY = getPage(e).pageY - mouseY;
  63. box.style.left = boxX + 'px';
  64. box.style.top = boxY + 'px';
  65. }
  66. }
  67. // 鼠标弹起,移除移动事件
  68. document.onmouseup = function () {
  69. box.onmousemove = null;
  70. }
  71. // 点击关闭按钮,盒子隐藏
  72. var box_close = document.getElementById('box_close');
  73. box_close.onclick = function () {
  74. box.style.display = 'none';
  75. }
  76. </script>
  77. </body>
  78. </html>

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/274805
推荐阅读
相关标签
  

闽ICP备14008679号