用mousedown来判断是否要开启移动,然后通过mousemove来获得移动的距离,实现移动;最后通过mouseup事件来判断移动结束了。
- <html>
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
- <style>
- body {
- margin: 0;
- background: #f2f6fe;
- }
-
- .jz{position:absolute;
- top:50%;
- left:50%;
- margin:-260px 0 0 -327px;
- width:654px;
- height:520px;
- }
- </style>
- <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
- </head>
- <body>
- <div class="jz">
- <div id="moveDiv" style="width:654px;height:520px;background-color:#4e6a81;position:absolute;border-radius: 5px;">
- <div id="moveBar" style="height:30px;border-radius: 5px;cursor: move;">
- </div>
- <iframe src='https://www.baidu.com' width='100%' height='100%' frameborder='0' style="border-radius: 5px;"></iframe>
- </div>
- </div>
-
-
- <script type="text/javascript">
- var dragJob=false;
- $(document).on("mousedown", '#moveBar', function (e) {
- dragJob = true;
- });
- document.onmousemove = function (e) {
- if (dragJob) {
- var e = e || window.event;
- var height = $(document.body).height();
- var width = $(window).width();
- var widthJob = $("#moveDiv").width();
- var heightJob = $("#moveDiv").height();
- var left = e.clientX - widthJob / 1;
- var top = e.clientY - 18 + $(document).scrollTop();
- if (top >= 0 && top < height - heightJob) {
- $("#moveDiv").css("top", top);
- }
- if (left >= 0 && left < width - widthJob) {
- $("#moveDiv").css("left", left);
- }
- return false;
- }
- };
- $(document).mouseup(function (e) {
- dragJob = false;
- });
- </script>
- </body>
- </html>
复制代码 |