[代码] jQuery实现的鼠标拖动浮层div

[复制链接]
本站网友  发表于 2022-6-9 22:02 |阅读模式

jQuery悬浮拖动div


用mousedown来判断是否要开启移动,然后通过mousemove来获得移动的距离,实现移动;最后通过mouseup事件来判断移动结束了。
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  5. <style>
  6. body {
  7.         margin: 0;
  8.     background: #f2f6fe;
  9.      }
  10.          
  11. .jz{position:absolute;
  12.         top:50%;
  13.         left:50%;
  14.         margin:-260px 0 0 -327px;
  15.         width:654px;
  16.         height:520px;
  17. }

  18. </style>
  19. <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
  20. </head>
  21. <body>
  22. <div class="jz">
  23.   <div id="moveDiv" style="width:654px;height:520px;background-color:#4e6a81;position:absolute;border-radius: 5px;">
  24.     <div id="moveBar" style="height:30px;border-radius: 5px;cursor: move;">
  25.         </div>
  26.         <iframe src='https://www.baidu.com' width='100%' height='100%' frameborder='0' style="border-radius: 5px;"></iframe>
  27.   </div>
  28. </div>
  29.   
  30.   
  31. <script type="text/javascript">
  32.     var dragJob=false;
  33.     $(document).on("mousedown", '#moveBar', function (e) {
  34.       dragJob = true;
  35.     });
  36.     document.onmousemove = function (e) {
  37.     if (dragJob) {
  38.       var e = e || window.event;
  39.       var height = $(document.body).height();
  40.       var width = $(window).width();
  41.       var widthJob = $("#moveDiv").width();
  42.       var heightJob = $("#moveDiv").height();
  43.       var left = e.clientX - widthJob / 1;
  44.       var top = e.clientY - 18 + $(document).scrollTop();
  45.       if (top >= 0 && top < height - heightJob) {
  46.         $("#moveDiv").css("top", top);
  47.       }
  48.       if (left >= 0 && left < width - widthJob) {
  49.         $("#moveDiv").css("left", left);
  50.       }
  51.       return false;
  52.     }
  53.   };
  54.   $(document).mouseup(function (e) {
  55.     dragJob = false;
  56.   });
  57.   </script>
  58. </body>
  59. </html>
复制代码

QQ|删帖注销|手机版|资源圈

GMT+8, 2024-4-26 22:36

Powered by Discuz!

© 20022-2026 Comsenz Inc.

快速回复 返回顶部 返回列表