拖拽滚动视图(一) (2)

拖拽滚动视图(一)

整体逻辑就一句话

移动的距离/总移动的距离=鼠标移动的距离/总长度

具体点就是

滚动条移动的距离/滚动条移动的总距离=鼠标移动的比较/总盒子可以移动的距离

上代码

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box-over { width: 60%; height: 60vh; overflow: auto; } .box { width: 140%; height: 150vh; margin: 200px auto; position: relative; border: 2px solid red; } .aaa { position: absolute; width: 50px; height: 50px; background-color: rgb(245, 230, 99); border: 10px solid rgba(136, 136, 136, .5); border-radius: 50%; } .aaa:hover { cursor: pointer; border-width: 20px; } .aaa:active { background-color: rgba(168, 218, 220, 1.00); } </style> </head> <body> <div> <div> <div></div> </div> </div> <script> /* mousedown 鼠标进入 * mousemove 鼠标移动 * mouseup 鼠标离开 * */ let box = document.querySelector("#box"); let ccc = document.querySelector("#ccc"); let over = document.querySelector('.box-over'); ccc.onmousedown = function (event) { //计算大盒子内部的宽高 let overW = box.getBoundingClientRect().width; let overH = box.getBoundingClientRect().height; //大盒子滚动条移动的距离 let overs = { x: over.scrollWidth - over.clientWidth, y: over.scrollHeight - over.clientHeight, } // 子盒子 let w = ccc.getBoundingClientRect().width / 2; let h = ccc.getBoundingClientRect().height / 2; // 大盒子-小盒子 let width = box.getBoundingClientRect().width - w; let height = box.getBoundingClientRect().height - h; // 按下的位置距离左侧的差值 let x = (window.pageXOffset + event.clientX) - this.offsetLeft let y = (window.pageYOffset + event.clientY) - this.offsetTop // 移动 document.onmousemove = function (e) { // 移动的坐标-左侧的坐标=子盒子的坐标 let x1 = e.pageX - x let y1 = e.pageY - y; if (-w < x1 && x1 < width) { ccc.style.left = x1 + 'px'; } if (-h < y1 && y1 < height) { ccc.style.top = y1 + 'px'; } // 移动的距离/总距离=鼠标移动的距离/总长度 // 滚动条移动的距离/滚动条移动的总距离=鼠标移动的比较/总盒子可以移动的距离 over.scrollLeft = x1 / overW * overs.x over.scrollTop = y1 / overH * overs.y } // 抬起 document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpszxs.html